# Question
Title: Which is better a computer science degree or a Software engineer degree?
I'm asking here so since you all have experience in or around game programming, that's what I want to do, and I’m trying to find as many options as I can before my senior year, which is next year. So do you have any opinions on the matter of which would give me a better education in programming?

Please no talking about anything other than the two degrees because I know of game programming degrees out there but I like to see which of these would provide the best alternate choice.

# Answer
Since you're asking on the game development forum, I'm assuming you're interested in a game development career. Both programs would be fine. They have some overlap, but they also would lead you in different directions.

A traditional computer science program is aimed at the more theoretical aspects of computing. You'd generally work in more traditional languages (C/C++/Java) and you'd spend a lot of time contemplating data structures, algorithms, and efficiency. CS majors typically are required to take a great deal of Math and Science. (I encourage our students to get a Math minor, because they're only one course away by the time they take our requirements.) The focus on math and theory are good preparation for certain kinds of game programming (say building game engines and creating lighting models.)

Software engineering has a different focus. Software engineering programs are typically more focused on business applications. The emphasis is on working with large teams of developers and building large software projects. Games are a form of business application, so the skills would be applicable.

Plenty of CS majors move into software engineering as they gain experience, but fewer people seem to move into CS after they've studied software engineering.
> 9 votes

# Answer
Both will give you a good education in programming. The primary difference is that Comp Sci will enable you to solve problems that no one else can, whereas Soft Eng is geared more towards delivering products to customers.

Both are necessary for good development, and will round out a good dev team. It depends on whether you are more science minded (answer questions) or engineering minded (design solutions).
> 4 votes

# Answer
Computer Science and Software Engineering should be different courses of study, but you'll find that most colleges only offer one. Most schools only offer a Computer Science program, which is essentially combining the two.

I attribute this to the relative youth of computer science as an area of study. Just a decade or two ago most Universities didn't have a computer science departments. The computer scientists where just part of the mathematics department.
> 2 votes

# Answer
The question that should really make your decision is "which is the better school?" When I'm reviewing resumes, I typically consider CS and SE degrees to be pretty much equivalent. I know the curricula differ, but not in any standard way between schools, and a high GPA in either degree serves the same purpose of imbecile-filtering.
> 2 votes

# Answer
I point you to my popular answer in the CS vs. Game Dev degree question.

Basically I feel it really doesn't matter all that much as to which degree you choose. Pick whichever one has courses that seem most interesting to you, take advantage of electives in your major that seem pertinent (i.e. algorithms, numerical analysis, etc) and learn game specific programming or do some mod work on the side.
> 0 votes

# Answer
take a look at http://computingcareers.acm.org/?page\_id=6, also see gaming and animation http://computingcareers.acm.org/?page\_id=10
> 0 votes

# Answer
The answer will depend on the school it is being offered at. My university offered both programs, but the software engineering major focused on embedded systems design. That meant a number of traditional programming and design course as well as some electrical engineering courses too.

The computer science major had two emphases, one in general programming and design, and one that focused on accounting (a lot of COBOL).

So, in the end, when looking at a school, also look at the emphases offered and you can always ask the people there on career paths that the major can lead to.
> 0 votes

# Answer
CS majors tend to have a better understanding of algorithms and other mathematical processes while being able to explain it to others. Engineering will actually put it to practical use and do things with it. The CS will spend two days hand making their own code. The engineer will take two hours copying it from a book of algorithms. The CS will either do research or try to go into an "engineering" job; however, the ENGINEER will always be better at an ENGINEERING job. The engineer will be making much more money. Too many people major in CS hoping to get a job right after graduation.. CS was originally made to go into grad school in Phd. Engineering was made to take the science and put it into practical use. Would you rather spend your life learning, or spend your life doing? That's what it comes down to. I haven't declared a major yet, but I'm probably going to declare computer engineering.
> -2 votes

---
Tags: education
---


# Question
Title: What's the equivalent of wglShareLists for Mac OS?
I'm trying to share lists between two contexts on Mac OS but despite my research I couldn't come up with an answer so far. I've found that NSOpenGLContext was able to initialize a context with a shared context but not to set it afterward.

What's the equivalent of wglShareLists on Mac OS?

# Answer
Here is Apple's documentation on the subject.

Essentially, you can either create an `NSOpenGLContext` (and in doing so, specify the original context you want to share using initWithFormat:shareContext: or use CGGLCreateContext's `share` parameter. I don't believe it is possible to share resources *after* initialization.

This will allow you to create a *second* context that shares all resources with the first context (the one you passed to one of the above functions). You have to make sure both contexts utilize the same GL profile.

There isn't a way to construct an `NSOpenGLView` (which you are probably using) with a shared context. Instead you'll probably have to swap the existing context out, or use that context as the main one from which you create the shared context.
> 3 votes

---
Tags: opengl, windows, macos
---


# Question
Title: How can I gain access to a player instance in a Minecraft mod?
I'm creating Minecraft mod with a pickaxe that takes away experience when you break a block. The method for taking away experience from a player is `addExperience` on `EntityPlayer`, so I need to get an instance of `EntityPlayer` for the player using my pickaxe when the pickaxe breaks a block, so that I can remove the appropriate amount of experience.

My pickaxe class currently looks like this:

```
public class ExperiencePickaxe extends ItemPickaxe {

public ExperiencePickaxe(int ItemID, EnumToolMaterial material){
    super(ItemID, material);
}

public boolean onBlockDestroyed(ItemStack par1ItemStack, World par2World, int par3, int par4, int par5, int par6, EntityLiving par7EntityLiving)
{
    if ((double)Block.blocksList[par3].getBlockHardness(par2World, par4, par5, par6) != 0.0D)
    {
        EntityPlayer e = new EntityPlayer(); // create an instance
        e.addExperience(-1);
    }

    return true;
}
}

```

Obviously, I cannot actually create a new `EntityPlayer` since it is an abstract class. How can I get access to the player using my pickaxe?

# Answer
I'm going to assume you're using the Forge API, given the parameters you listed.

`EntityLiving` is an abstract type representing living entities like players and mobs. When it is passed into your block break event, it indicates the entity which broke the block. It's not guaranteed to be a player, so you need to try to cast it to the subtype that represents a player:

```
if( par7EntityLiving instanceof EntityPlayer ) {
  EntityPlayer player = (EntityPlayer) par7EntityLiving;
  player.addExperience(-1);
  // OR
  player.addExperienceLevel(-1);
}

```

If the `instanceof` check fails, then the parameter did not represent an `EntityPlayer` object and the block break was caused by something else.
> 8 votes

---
Tags: java, minecraft-modding
---


# Question
Title: Why won't my vertex buffer render in GLFW3?
I have started to try to learn OpenGL, and I decided to use GLFW to assist in window creation. The problem is, since GLFW3 is so new, there are no tutorials on it or how to use it with modern OpenGL (3.3, specifically).

Using the GLFW3 tutorial found on the website, which uses older OpenGL rendering (`glBegin(GL_TRIANGLES)`, `glVertex3f()`, and such), I can get a triangle to render to the screen. The problem is, using new OpenGL, I can't get the same triangle to render to the screen.

I am new to OpenGL, and GLFW3 is new to most people, so I may be completely missing something obvious, but here is my code:

```
static const GLuint g_vertex_buffer_data[] =
{
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};

int main(void)
{
    GLFWwindow* window;

    if(!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW.");
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(800, 600, "Test Window", NULL, NULL);
    if(!window)
    {
        glfwTerminate();
        fprintf(stderr, "Failed to create a GLFW window");
        return -1;
    }
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if(err != GLEW_OK)
    {
        glfwTerminate();
        fprintf(stderr, "Failed to initialize GLEW");
        fprintf(stderr, (char*)glewGetErrorString(err));
        return -1;
    }

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    GLuint programID = LoadShaders("SimpleVertexShader.glsl", "SimpleFragmentShader.glsl");

    GLuint vertexBuffer;
    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    while(!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(programID);

        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glDisableVertexAttribArray(0);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glDeleteBuffers(1, &vertexBuffer);
    glDeleteProgram(programID);

    glfwDestroyWindow(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}

```

I know it is not my shaders, they are super simple and I've checked them against GLFW 2.7 so I know that they work. I'm assuming that I've missed something crucial to using the OpenGL context with GLFW3, so any help locating the problem would be greatly appreciated.

# Answer
> 4 votes
You define your vertex data as `GLuint`s:

```
static const GLuint g_vertex_buffer_data[] =

```

However you bind this data as `GL_FLOAT`s:

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

```

`-1.0f` when cast to `GLuint` and then interpreted as a `float` represents `NaN` (not a number) and lead to unspecified results, as the OpenGL 3.3 Core Profile specification states:

> The special values `Inf` and `Inf` encode values with magnitudes too large to be represented; the special value `NaN` encodes “Not A Number” values resulting from undefined arithmetic operations such as `0/0`. Implementations are permitted, but not required, to support `Inf`s and `NaN`s in their floating-point computations. Any representable floating-point value is legal as input to a GL command that requires floating-point data. The result of providing a value that is not a floating- point number to such a command is unspecified, but must not lead to GL interrup- tion or termination.

And since I don't see anything else obviously wrong with your code, changing `GLuint` to `GLfloat` should do the trick.

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


# Question
Title: Spritesheet filesize gets huge after compiling
I have a 14x2 spritesheet which has 125 Kb in raw .png. But as soon as I compile that to .xnb, it mutates to 4 MB.

So my question is: Why is that? And how can I fix that?

# Answer
> 3 votes
I believe images in xnb format are uncompressed so image file size is purely a function of image size and colour depth.

Width * Height * Depth = Size

If your image is 1024px square at 32 bits per pixel, it'll be 4mb in size.

**Edit**

You could try using the DxtCompressed option, in the solution explorer \> content project \> image file \> properties \> texture format - change Color to DxtCompressed

# Answer
> 3 votes
The resources compiled in Debug mode generally comes bigger than the original. Try to compile in Release mode and see the size of the file in the Release folder.

---
Tags: xna, performance, memory
---


# Question
Title: Writing to a structured buffer with a compute shader (D3D11)
I have some problems writing to a structured buffer. First I create a structured buffer that is filled with float values beginning from 0 to 99. Afterwards a copy the structured buffer to a CPU accessible buffer is made to print the content of the structured buffer to the console. The output is as expected (Numbers 0 to 99 appear on the console). Afterwards I use a compute shader that should change the contents of the structured buffer:

```
RWStructuredBuffer<float>   Result : register( u0 );

[numthreads(1, 1, 1)]
void CS_main( uint3 GroupId : SV_GroupID )
{
    Result[GroupId.x] = GroupId.x * 10;
}

```

But the compute shader does not change the contents of the structured buffer.

The source code can be found here (main.cpp): https://bitbucket.org/Vertexwahn/cmakedemos/src/4abb067afd5781b87a553c4c720956668adca22a/D3D11ComputeShader/src/main.cpp?at=default

FillCS.hlsl: https://bitbucket.org/Vertexwahn/cmakedemos/src/4abb067afd5781b87a553c4c720956668adca22a/D3D11ComputeShader/src/FillCS.hlsl?at=default

# Answer
Your dispatch call `Dispatch( 100, 0, 0 )` is not actually creating any thread groups. You need (100, 1, 1). The total number of thread groups is the product of the three dimensions, so any zero dimension will nullify the whole thing.

Also, you're not re-copying the structured buffer to the staging buffer after running the compute shader.
> 3 votes

---
Tags: c++, shaders, directx11
---


# Question
Title: What is the standard technique for shifting the frames of a sprite according to user input?
From my own experience, I developed two techniques for changing the sprites of a character that's reacting to user input -- this in the context of a classic 2D platformer.

The first one is to store all character's pixmaps in a list, putting the index of the currently used pixmap in an ordinary variable. This way, every time the player presses a key -- say the right arrow for moving the character forward -- the graphics engine sees what's the next pixmap to draw, draws it, and increments the index counter. That's a pretty common approach I believe, the problem is that in this case the animation's quality depends not only on the number of sprites available but also on how often your engine listens to user input.

The second technique is to actually play an animation every key press event. For this you can use any sort of animation framework you want. It's only necessary to set the timer, the animation steps and to call the animation's `play()` method on your key press event handler. The problem with that approach is that is lacks responsiveness, since the character won't react to any input while the current animation is still being played.

What I want to know is whether you are using one of these techniques -- or something similar -- in your games, or whether there's a standard method for animating sprites out there that's widely known by everybody but me.

# Answer
> 2 votes
You should really keep the code for advancing animations and taking input separate.

In general, you want to keep drawing and input as separate as possible. Most games still animate when there's no user input. (The notable exception being rougelikes.) The structure of code should reflect that one does not depend on the other.

I suggest using some sort of state machine which keeps track of which animation currently needs to be played.

Then, you can just update the active animation each frame. The animation should be updated before each and every frame is drawn to the screen, not on each input tick. That way, animation will be smooth regardless of user input.

**Remember to check the delta time between frames if you're not using a fixed framerate though.** Animation assumes that frames will be seen at certain times, so letting the game loop advance the frame count whenever it decides to draw to the screen will give you problems if the time between game ticks is not the spacing the artist intended.

> The problem with \[just running an animation on keypress\] is that is lacks responsiveness, since the character won't react to any input while the current animation is still being played.

You probably want to stop the current animation when the input state changes. Though, if you cut one animation and start up one which is quite different, it will jerk

In fighting games, this is called a cancel.

It can be useful if you want the animation to feel faster or punchier, but it's not always what you want. For smoother transitions, you'll need to make transition frames, or limit when certain transitions can occur. Both techniques are used in fighting games. Understanding framedata is critical to high-level fighting game play, so you might want to poke around in the fighting game community to better understand this animation style.

This is why a state machine is very helpful. It will allow you to define transitions between different states, and callbacks for when the transitions occur.

It might not be standard to use an official state machine library for this, but why roll your own when a state machine library can do the job for you?

# Answer
> 2 votes
I solve this problem by keeping the animation code and the drawing code separate. I have a series of images for each part of the animation, and the code merely selects which one to draw. The drawing is handled elsewhere. My game loop, simplified for a single animated image, looks something like this:

1. Process user input. This might alter the position where the sprite is drawn.
2. Run animation code. If it's time for the next image, change the current sprite index. If the user did something, reset to the base image.
3. Blank the screen.
4. Draw whatever image is at the current sprite index.

This mostly aligns with your option #1, but the key difference is the graphics engine does not change which sprite to draw. Separation of concerns is a Good Thing.

# Answer
> 2 votes
I'd recommend you that you split the Input, Action, State and Animation in separate systems/layers.

For instance:

Input 'tap forward twice' Action 'DoRunForward' State 'RunningFoward' Animation 'RunningFoward'

The Animation layer would only concern in handle the animation logic. Rotate, scale, translate, flip images, run the key frames in the sprite sheet, execute loops etc.

It would be the State layer that would process the gameplay logic. Move the character, play sounds, change the character animation etc.

It's easier to implement state changing in the middle of a running state this way.

# Answer
> 1 votes
You can also use 2D Bones Animation. For the ”theory” you can read this. It's 3D but it can be applied to 2D by just ignoring the Z-axis.

There are some frameworks for different languages:

---
Tags: 2d, animation
---


# Question
Title: Finding the shorter turning direction towards a target
I'm trying to implement a type of movement where the object gradually faces the target. The problem I've run into is figuring out which turning direction is faster. The following code works until the object's orientation crosses the -PI or PI threshold, at which point it will start turning into the opposite direction

```
void moveToPoint(sf::Vector2f destination) {
    if (destination == position) return;

    auto distance = distanceBetweenPoints(position, destination);
    auto direction = angleBetweenPoints(position, destination);

    /// Decides whether incrementing or decrementing orientation is faster
    /// the next line is the problem
    if (atan2(sin(direction - rotation), cos(direction - rotation)) > 0 ) {
        /// Increment rotation
        rotation += rotation_speed;
    } else {
        /// Decrement rotation
        rotation -= rotation_speed;
    }

    if (distance < movement_speed) {
        position = destination;
    } else {
        position.x = position.x + movement_speed*cos(rotation);
        position.y = position.y + movement_speed*sin(rotation);
    }
    updateGraphics();
}

```

'rotation' and 'rotation\_speed' are implemented as custom data type for radians which cannot have values lower than -PI and greater than PI. Any excess or deficit "wraps around". For example, -3.2 becomes ~3.08.

# Answer
> 3 votes
Assuming `direction` is the desired rotation angle to turn toward, just subtract `direction - rotation` and wrap the result into the \[-pi, pi\] range. Then its sign should indicate the correct direction to turn. There's no need to munge it through any trigonometric functions.

# Answer
> 0 votes
This is faster because it does not have to calculate the atan. It just determines if your angle is greater or lesser than Path.PI.

```
/**
* Gets the angle that is in the range [-2*PI, 2*PI] and returns the equivalent angle
* that is in the (-PI, PI] range.
*/
void function normalizeAngle(a:Number):Number {
    if (a > Math.PI) {
        return a - 2 * Math.PI;
    } else if (a <= -Math.PI) {
        return a + 2 * Math.PI;
    }
    return a;
}

// usage example:
var rotationDifference:Number = normalizeAngle(targetRotation - originalRotation);

```

On each update you rotate a portion of the rotationDifference.

---
Tags: movement, rotation
---


title: Gap in parallaxing background loop

text:
# Question
Title: Gap in parallaxing background loop
The bug here is that my background kind of offset a bit itself from where it should draw and so I have this line. I have some troubles understanding why I get this bug when I set a speed that is different then 1,2,4,8,16,...

In main class I set the speed depending on the player speed

```
 bgSpeed = -(int)playerMoveSpeed.X / 10;

```

and here's my background class

```
class ParallaxingBackground
    {
        Texture2D texture;
        Vector2[] positions;
        public int Speed { get; set;}

        public void Initialize(ContentManager content, String texturePath, int screenWidth, int speed)
        {
            texture = content.Load<Texture2D>(texturePath);
            this.Speed = speed;
            positions = new Vector2[screenWidth / texture.Width + 2];
            for (int i = 0; i < positions.Length; i++)
            {
                positions[i] = new Vector2(i * texture.Width, 0);
            }
        }
        public void Update() {
            for (int i = 0; i < positions.Length; i++)
            {
                positions[i].X += Speed;
                if (Speed <= 0)
                {
                    if (positions[i].X <= -texture.Width)
                    {
                        positions[i].X = texture.Width * (positions.Length - 1);
                    }
                }
                else
                {
                    if (positions[i].X >= texture.Width*(positions.Length - 1))
                    {
                        positions[i].X = -texture.Width;
                    }
                }
            }
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            for (int i = 0; i < positions.Length; i++)
            {
                spriteBatch.Draw(texture, positions[i], Color.White);
            }
        }

    }

```

# Answer
> 4 votes
Your problem happens when you reuse the background and put it the other side. Change this:

```
 if (positions[i].X <= -texture.Width)
 {
      positions[i].X = texture.Width * (positions.Length - 1);
 }

```

To this:

```
 if (positions[i].X <= -texture.Width)
 {
      positions[i].X += texture.Width * positions.Length;
 }

```

So, add (`+=`) instead of overwrite (`=`).

Same here, change this:

```
if (positions[i].X >= texture.Width*(positions.Length - 1))
{
     positions[i].X = -texture.Width;
}

```

To this:

```
if (positions[i].X >= texture.Width*(positions.Length - 1))
{
     positions[i].X -= texture.Width * positions.Length;
}

```

Don't forget to get rid of the `- 1` two times.

---
Tags: xna, c#, parallax-scrolling
---


title: Map building - Tower Defense

text:
# Question
Title: Map building - Tower Defense
Before diving too deep into my question, let it be known that I am learning as far as java script goes and figured a simple Tower Defense game would be an excellent way to learn things.

So I have found a simple background image with a path drawn on it and my question is how would I go about building a path so that I can animate my objects. Would I have to take the image and overlay a grid system, or can I store the path in some sort of array and have my objects move across it?

Here is the background image:

# Answer
There's a few options you have, since your question is fairly high level, I'll provide these high level suggestions:

1. Create a grid in code, and overlay the image on it
2. Using the color of your path, assign the grid spaces that match "path color" as walkable.
3. Use A\* to find a path from start to finish.

There's some tweaking you can do with this one, altering the grid size to make for finer details, and using some kind of marker on the map to ensure the grid is aligned properly.

Another option:

1. Convert the map into tiles
2. Create a tiled map using the tiles you created above
3. Ensure the tiles used for making the path are "walkable"

This method will one of the most time intensive, but has the result of providing you with the most consistent verifiable results. You can also use the tiles you've created to automatically produce variations of the same map, altering your path to take different directions.
> 4 votes

# Answer
I think the most flexible way is to handle an array of segments that describes the path, and to move onto each segment depending on time elapsed and item speed.
The accuracy is ok as long as you take short segments.

Since it's not that hard to handle, we'll just go for an array of 2n points where index 2\*p is the x of the pth point and 2\*p+1 is its y.
Then, on each update of the game, a given time elapsed : this time multiplied by the speed will give you the distance you need to travel within the segments ( d = v * t ).
You go forward (or backward) a given distance by 'eating' each segment one after another. If you cannot eat up all of a segment, just eat a part of it (a ratio).

I made i fiddle for this, it works quite well : http://jsfiddle.net/xTf9P/1/

```
// PathFollower : Class describing an object that will
//   follow a path depending on its speed.
//   It will 'bounce' if it encounters a path border.
//   use draw() to draw and move(dt) to make it move. (dt in ms)
//       path is an array [x0,y0, x1,y1, x2,y2, ...]
//       pathLength[i] = length of the ith segment.
function PathFollower(speed, path, pathLength, color) {
    this.x = 0;
    this.y = 0;
    this.speed = speed ;
    this.path  = path  ;
    this.pathLength = pathLength;
    this.color = color ;
    this.pathIndex = 0 ;
    this.ratio     = 0 ;  // ratio of position within current segment.
  }

PathFollower.prototype = {
   draw : function() {
       var width = 14 + 2*Math.sin(Date.now()/200);
       ctx.strokeStyle = this.color;
       ctx.strokeRect(this.x - width, this.y-width,
                                      2*width, 2* width);
   },
   move : function(dt) {
    // distance to travel
    var distance = Math.abs( dt * this.speed );
    // speed sign
    var sign     = (this.speed > 0) ? 2 : -2 ;
    var segLength=0, remainingSegLength=0;
    while (distance >0) {
            // current segment length
            segLength = this.pathLength[this.pathIndex >> 1];
            // remaining segment length : depends on speed sign
            if (sign >0) {
                       if (this.ratio == 0)  remainingSegLength=segLength;
                       else remainingSegLength = (1-this.ratio) * segLength;
            } else {
                       if (this.ratio == 1) remainingSegLength=segLength;
                       else remainingSegLength = this.ratio * segLength;
            }

            if (remainingSegLength < distance) {
                 // if this segment cannot eat up the distance, skip to next.
                 distance -= remainingSegLength; // eat
                 this.ratio = (sign >0) ? 0 : 1; // new ratio within segment
                 // loop if encounter the end of the path
                 if ( (sign<0 && this.pathIndex == 0) ||
                      (sign>0 && this.pathIndex == this.path.length-4))  {
                        this.speed = -this.speed;
                        this.ratio= (this.speed >0) ? 0 : 1;
                       break;
                    }
                  // iterate
                  this.pathIndex +=sign;
                } else {
                   // let us eat as much of this segment as we can.
                   var ratio = distance / segLength ;
                   this.ratio += (sign>0) ? ratio : -ratio;
                   break;
                }
          }
  // compute new (x, y)
  this.x = this.path[this.pathIndex] +
       this.ratio *(this.path[this.pathIndex+2] - this.path[this.pathIndex]) ;
  this.y = this.path[this.pathIndex+1] +
       this.ratio *(this.path[this.pathIndex+3] - this.path[this.pathIndex+1]);

  }
}

```

Obviously, you'll want your monster not to follow the exact same path : handle a constant offset or a distance to the curve for each of them to show separately.

(the fiddle for the very code above is here : http://jsfiddle.net/JYYmA/3/)
> 1 votes

# Answer
Since the other answers are more grid based, I thought I'd offer a path solution.

Disclaimer: I usually implement grids in my own games, and it'd be useful for when you have the user place tiles.

Anyways, what I'd do is first draw the path you want on the canvas. This can be done using something like the below code (taken from here)

```
context.beginPath();          // Begin your path
context.moveTo(100, 150);     // Move the starting cursor to 100, 150
context.lineTo(450, 0);       // Maps out 450 in the x dir
context.lineTo(0, 50);        // Maps out 50 in the y dir
// Repeat the above two lines to add more connected segments)
// Negative numbers go down or to the left
context.stroke();             // Actually draws the line

```

Once you figure out the right path, you can figure out a step by step traversal of it. So for example if you want to animate the path, we can take the 450 in the right direction and break it down over time, so depending on what speed you want your object to move, you can move it 5px every 20ms or something.

So far this solution has been completely hardcoded, making it pretty bad. It does help to get an understanding though and acts sort of like psuedocode for figuring out how to do it automatically.

Since we'd want out code to work on multiple levels, what you could do is create a level file, which you can place the commands for walking the route. The first line of the file could be the background that corresponds to the path. Then it's easy enough to parse the file taking in the background and then the path your object can go!

EDIT: I sort of forgot to answer the question. The way I'd store the path, would be however you find it most convenient.

One way would be to parse the level file, taking each command and storing it into a position/movement object that has an x and a y that you place into an array.

Example:

```
Move x 250
Move y 50
Move x 50
Move y -50
Move x 100

```

Would turn into

```
[(250,0), (0,50), (50, 0), (0,-50), (100,0)]

```

Then when you read your array, you can take the x and the y of the first index and put them into xMov and yMov (since you just use perpendicular paths you only have something stored in x or y at a time).

After every movement you subtract however far you went in that update from either xMove or yMov. Once you reach 0 in both, you read the next index of the array and store it in xMov and yMov again. Repeat until it finishes and your object is off the screen. Note you will need an xMov, yMov, and index variable for each object, so if you have more than one make sure you're using the correct one.

Essentially this looks overly complicated and maybe like nonsense, but it's really not too hard to implement. You could do the same exact thing as a grid since essentially we're using the pixels as a grid here.
> 0 votes

---
Tags: path-finding, html-canvas, tower-defense
---


# Question
Title: how to link a c++ object to a local variable in Lua
I'm completing my scripting interface with Lua, but recently I've stuck at some point. I have several functions for my `Entitiy` events like `Update()`. I have a function called `create_entitiy()` which instantiate a new entity from a given entity index:

```
function Update()
  local bullet = create_entity(0, 0, "obj_bullet")
end

```

`create_entity` returns a table which is the properties of the created entity. Now how can I make a connection between `bullet` variable and my newly created object?

Right now for previously added objects to the scene, I simply set a global table for each of them and then after every call to `Update()`, I go through registered names to find object tables and perform new changes. Like the one below:

```
function Update()
  if keyboard_key_press(vk_right) then obj_player.x += 3
end

```

I can get `obj_player` table because I know its name from C++, plus I can get it as a global table and simply reach for the first instance named `obj_player`.

Is there any solution for me to make `bullet` variable act like this?

I was thinking to get all `local` variables in `Update()` function and check for every one to see if is it table and it has an unique field attached to it like `id`, this way I can determine that this is an object table and do the rest of the process.

By the way, is this interface going to work easier with `luaBind` if I implement it?

**Bottom line:**

How can I make a local variable in Lua that receives a table from `create_entity` function and track that local variable to capture it from C++.

e. g.

```
function Update()
  local bullet = create_entity(0, 0, "obj_bullet")
  bullet.x = 10 <== Commit a change in table
end

```

Now I want to get variable `bullet` from C++. And it's not just this variable, there might be a ton of these local variables with different names.

# Answer
> 3 votes
As Sean Middleditch said in the comments, locals in Lua *reference* tables, not copy them. Therefore if you have some code like

```
local bullet = create_entity(0, 0, "obj_bullet")
bullet.x = 10    -- Commit a change in table

```

what you really need to keep track of is *not* the local variable `bullet`, but rather the table returned by `create_entity`. There can be any number of local variables, fields, etc. that reference this same entity, but (as far as I understand your question) you don't need to keep track of all of them, only the single table they refer to.

So all you need to do is, in the implementation of `create_entity`, store a reference to the created table someplace where you can retrieve it later. For instance, you might have a global table of all entities, keyed by the entity's ID, and reference the entity table from there. You could then find this table from C++ (since its name is fixed) and walk over its entries whenever you needed to check for updates.

---
Tags: c++, scripting, lua
---


# Question
Title: Why is my collision detection not accurate?
After trying and trying, I still cannot understand why the leg of character exceeds the wall but no clipping issue when I hit the wall from below. How should I fix it to make him stand still on the wall?

From collideWithBox() function below, it shows that `playerDest.Y = boxDest.Y - boxDest.height;` will get the position the character should standstill on the wall. Theoretically, the clipping effect won't be happen as the character hit the box from below works with the equation `playerDest.Y = boxDest.Y + boxDest.height;`.

```
void collideWithBox()
{
    if ( spriteCollide(playerDest, boxDest) && keyArr[VK_UP])
        //playerDest.Y += 50;
        playerDest.Y = boxDest.Y + boxDest.height;
    else if ( spriteCollide(playerDest, boxDest) && !keyArr[VK_UP])
        playerDest.Y = boxDest.Y - boxDest.height;
}

void initPlayer()
{
    //  Create texture.
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "player.png", 169, 44,
        D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
        D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
        NULL, NULL, &player);

    playerRect.left = playerRect.top = 0;
    playerRect.right = 29;
    playerRect.bottom = 36;

    playerDest.X  = 0;
    playerDest.Y  = 564;

    playerDest.length = playerRect.right - playerRect.left;
    playerDest.height = playerRect.bottom - playerRect.top;
}

void initBox()
{
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "brock.png", 330, 132,
        D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
        D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
        NULL, NULL, &box);

    boxRect.left = 33;
    boxRect.top = 0;
    boxRect.right = 63;
    boxRect.bottom = 30;

    boxDest.X = boxDest.Y = 300;

    boxDest.length = boxRect.right - boxRect.left;
    boxDest.height = boxRect.bottom - boxRect.top;
}

bool spriteCollide(Entity player, Entity target)
{
    float left1, left2;
    float right1, right2;
    float top1, top2;
    float bottom1, bottom2;

    left1 = player.X;
    left2 = target.X;
    right1 = player.X + player.length;
    right2 = target.X + target.length;

    top1 = player.Y;
    top2 = target.Y;

    bottom1 = player.Y + player.height;
    bottom2 = target.Y + target.height;

    if (bottom1 < top2) return false;
    if (top1 > bottom2) return false;

    if (right1 < left2) return false;
    if (left1 > right2) return false;

    return true;
}

```

# Answer
`playerDest.Y = boxDest.Y - boxDest.height`

should be

`playerDest.Y = boxDest.Y - playerDest.height`
> 2 votes

---
Tags: c++, collision-detection
---


# Question
Title: Windows Phone XAML and XNA Apps with Game Components
I am using the Windows Phone Template "Windows Phone XAML and XNA Apps" and targeting Windows Phone 7/8. Most examples show your game inheriting from `Microsoft.Xna.Framework.Game` and then adding `Microsoft.Xna.Framework.GameComponent` items to the `Components` collection. But as my game page inherits from `PhoneApplicationPage` there isn't a `Components` collection or a `Game` property.

How can I use `GameComponent` from within `PhoneApplicationPage`?

# Answer
> 3 votes
You can't. Important parts of their infrastructure are contained within the `Game` class. (Also, `GameComponent`'s constructor takes a `Game`.)

My advice (as always) is to **not use `GameComponent`**. Like the `Game` class itself, game components are a completely optional part of the framework. And often they're more trouble than they're worth.

You're better off just creating "normal" classes - however you like - and making a normal `List` to contain them. If you need any other functionality that the game component infrastructure provides, that's pretty simple to implement too.

For reference, that functionality basically amounts to: a mechanism for adding/removing/re-ordering items while the list is being iterated (as simple as copying the list before iterating), sorting components, disabling/hiding components, and calling the various methods for you at the obvious times.

That being said, if you *really* want to use something identical to `GameComponent`, you could take the relevant code from ExEn (or MonoGame, although I'm not sure what their code for this is like). The code in question is confined to the GameComponents directory and should be fairly independent. Unlike XNA itself, in ExEn the magic happens in the resuable `GameComponentCollection` class instead of deep inside the `Game` class.

(I looked into using XNA's own code for this - but it's not really possible to do in a way that isn't terrifying.)

---
Tags: xna-4.0, windows-phone-7
---


# Question
Title: How would one go about integrated python into a c++ written game for the use of user-made scripts
I'm quite new to game development (not the site) and I'm currently just trying to educate myself about some certain things before I really begin working and a game.

anyway, I'd like to know what basic algorithm/outline of how a game would be coded effeciently with the implementation of user coded scripts for gameplay and levels that are written in python,

Is this even possible? would all the features of python be avalible? like say "multi-threading"?

# Answer
I can't tell you explicitly what to do as this is a high level question, but if you are indeed new to game development, then I can give you some advice.

**Consider using a component system**

I'm biased here as I almost exclusively use the component system in my own project, but it really is a great design pattern. It very easily allows you to create very complex functionality. You'll need to research this yourself if you haven't heard of it before, but here is a link to get you started if not:

https://stackoverflow.com/questions/1901251/component-based-game-engine-design

**Decouple your scripting system from your C++ code as much as possible**

This is somewhat related to using a component system. You're going to want to break your code into self contained units as much as possible, that will will eventually be referable from your python scripts.

**If you implement your scripting system correctly, performance most likely won't be a problem**

I'm treading on thin water here, but it needs to be said. If you're just making a simple game, then the performance penalty associated with using python or any other such interpreted language will not be a worry *as long as* you use it appropriately. What I mean by this is that your collision detection code etc should not be implemented using python. What you want to do is reference C++ code within your python files.

*You will end up making extensive use of whatever event system you decide to implement*, so don't overengineer it but make sure it is easy to maintain and consider what you actually need it to do. If necessary, get out some paper.

Honestly, don't worry about coding 'efficiently' to begin with. Just don't do anything silly like try to implement part of your rendering system in python, unless, of course, you can take that performance hit.

**Above all**

Get something working. You can very easily get bogged down in the specifics to begin with. What I would advise is to just get yourself to a scenario where you can confidently call functions from python, have that python script modify some of your internal object states in C++ and then see where you are.

Addressing your last point, multi-threading: optimise as and when you have to, not pre-emptively as you will **waste time**. If there are things you can do which will improve performance with little or no extra development time required then by all means do it, but generally, you will want to see whether you hit performance targets and then **profile your code**
> 2 votes

---
Tags: c++, python, scripting
---


# Question
Title: how to calculate sky color hue in a specific way?
I have a day cicle in my game. I want to add a bluish hue to my terrain in the early morning and evening-night. I want to start transitioning from 0 hue color to the full hue color at 20 PM and reach the full color at 0 AM, then start fading back and reach 0 hue color at 7 AM.

Given a time of day in hour and minute, or seconds, how can I write a function to calculate the hue color correctly?

# Answer
It sounds like you want a simple implementation. So here's what you can do.

* Pick your night-time hours. It sounds like you want 8pm to 7am (11 hours)
* Pick your formula. Is it linear transitions all throughout, or is there a time of "constant" daylight? Let's assume you always want the time moving.
* Experiment in an image editor. Take a screenshot of your game, overlay a blue layer, and see what the maximal transparency is that you want -- say 50%.

If you decide on these parameters (tweak to your liking), the rest is easy; you just need a formula for changing the alpha. It will start at 0 (8pm), and at 0 (7am), and peak at 50% (1:30am).

The formula should be pretty easy to calculate from this. You use the time difference from now to the peak time, and use that to swet the alpha of the blue overlay.
> 1 votes

---
Tags: animation, timer, color, sky
---


# Question
Title: Why is concept art not signed by the author?
I am a starting concept artist who would like to enter the gaming industry. I noticed that some AAA titles show their concept art with no artists signature (only a reference to game the game, such as for Star Wars The Old Republic: *2013 ALL RIGHTS RESERVED BioWare, LucasArts*).

I asked myself a question, what possible harm could my autograph cause on the public concept art if I am not a well known concept artist such as Adam Adamowicz (who did concepts for Skyrim). Why would a prospective boss tells me not to leave my "finger print" on the picture despite, the fact that I am a very talented artist?

# Answer
> 3 votes
Most of the concept art you're likely familiar with from big names in the industry was produced for a game, while the artist was in the employ of some company. That often means the ownership of the copyright falls to the company itself. It's similar to how all the code I've written while working for my current employer is not mine to keep if I were to leave the studio.

As a result, it may be company policy not to sign art produced for a game. Possibly for reasons Steve H pointed out in his comment (they want to continue to make use of the art, even after you leave or even after your name becomes sullied in some fashion that they'd want to distance themselves from... although the former is more likely than the latter I'd hope). Possibly simply because they want to keep it "unadulterated."

I just checked, and the large of some of Daniel Dociu's work I have in my room isn't signed, for example.

That said, I'd sign everything you create on your own time for your own projects, if I were you. It's only after you get a job in the industry (and if that job requires you to not sign anything you do as part of that job) that this will affect you.

---
Tags: art, intellectual-property
---


title: Collision detection with entities/AI

text:
# Question
Title: Collision detection with entities/AI
I'm making my first game in Java, a top down 2D RPG. I've handled basic collision detection, rendering and have added an NPC, but I'm stuck on how to handle interaction between the player and the NPC.

Currently I'm drawing out my level and then drawing characters, NPCs and animated tiles on top of this. The problem is keeping track of the NPCs so that my Character class can interact with methods in the NPC classes on collision.

I'm not sure my method of drawing the level and drawing everything else on top is a good one - can anyone shed any light on this topic?

# Answer
> 2 votes
I wouldn't be afraid to just keep track of the enemies in an ArrayList or something and loop through the enemies to check explicitly if they collide.

```
for(Enemy enemy : enemiesArray) {
    if(player.collidesWith(enemy))
        //Do something
}

```

Unless you have a **lot** of enemies or you're crammed for performance, I don't see anything wrong with this approach.

---
Tags: java, 2d, collision-detection, rpg, npc
---


# Question
Title: Game state management (Game, Menu, Titlescreen, etc)
Basically, in every single game I've made so far, I always have a variable like "current\_state", which can be "game", "titlescreen", "gameoverscreen", etc.

And then on my Update function I have a huge:

```
if current_state == "game"
  game stuf
  ...
else if current_state == "titlescreen"
  ...

```

However, I don't feel like this is a professional/clean way of handling states. Any ideas on how to do this in a better way? Or is this the standard way?

# Answer
> 14 votes
Since you are talking about screens, I feel it's best to separate all that logic into different Screens. What I normally do:

Define an interface called screen, and have multiple screens implement it. Like LoadingScreen, MainMenuScreen, GameScreen, GameOverScreen, HighScoreScreen etc. In your game you put a variable that holds the current screen. Each loop, you call screen.update() and render the current screen. This will save you a lot of "if this state do that" as your state is defined by current screen.

This will separate your logic very nicely.

Example code:

```
### Screen interface ###
public interface Screen {

    public void show();

    public void update(float delta);

    public void render(float delta);

    public void hide ();
}

### An implementation of screen ###
public class MainMenuScreen implements Screen {

    private Game game;

    public MainMenuScreen(Game game) {
        this.game = game;
    }

    public void show() {
        // init stuff
    }

    public void update(float delta) {
        // react to clicks, update animations etc.
        if (buttonwasclicked) {
            game.setScreen(new GameScreen(game)); // change the screen
        }
    }

    public void render(float delta) {
        // draw everything
    }

    public void hide() {
        // release all resources, as the screen is being hidden
    }
}

### Game, drawing the appropriate screen ###
public class Game {

    public Screen screen;

    public void update() {
        screen.update(getDeltaTime);
        screen.render();
    }

    public void setScreen(Screen screen) {
        this.screen.hide();

        this.screen = screen;
        this.screen.show();
    }
}

```

Or depending on your game setup, you maybe have an infinite loop as your game.

```
while(true) {
    calculatetimesincelastframe()
    screen.update(time);
    screen.render(time);
}

```

# Answer
> 5 votes
If you're already using Middleclass, there's an excellent state-machine library to go along with it called Statefull. It's easy to use and esposes the same ideas that Matsemann proposed.

# Answer
> 2 votes
If your `current_state` variable is a string, then this is really easy in Lua:

```
game_states = {}
function game_states.game()
    -- game stuff
end
function game_states.titlescreen()
    -- title screen stuff
end

-- then, inside the Update function:
game_states[current_state]()

```

# Answer
> 1 votes
What I do is roughly as follows:

I have a directed acyclic graph data structure, which is essentially just a bunch of nodes that point at each other. Each node represents a game system. e.g. the UI, the world, the input, the rendering. And each node points at other nodes that come before or after it. Once all the nodes are in place, it's easy to flatten it out into a simple list. Setting up this DAG is the first thing I do during the game's start up. Any time I want to add a new system, say AI, I can just say write that code then tell my game what it depends on and what should depend on it.

My main game loop comes after that and simply runs each system in order. First input is handled, then world updates, then other stuff... UI is near the end, and rendering is last. When the game first starts, there is no world or physics or AI, so those steps are essentially skipped, and just the title screen is displayed. When the you start the game proper, the UI sends a message to the world system to turn on, and it just takes care of itself. Managing game state just means turning on and off the various systems. Each system has it's own set of state information that is handled more or less independently of all others (That's not *totally* true actually, many systems act on the same set of data - the UI system for example grabs data from the world to display info for example. The AI system also needs to look at and send messages to entities in the world).

# Answer
> 1 votes
Here's how I organize my states in Lua + Love2d. It avoids the long if/then statements.

First, I create a basic class that contains an update(dt) and render() methods. You can also give it event handling methods, like onKeyDown(key). I call this class Stage, but any object that implements the methods will work. Then, I make an instance of that class for each game state, implementing the necessary methods. I then create a key/value table with the state's name and the instance of the state. Then keep track of the currentState at the global scope so the states can change it when a certain condition is met.

```
states = {}
states["title"] = title   -- Where title implements Stage class.
states["game"] = game     -- You could create the instance of 'game' lazily too.
currentState = "title"

function love.update(dt)
    if states[currentState] ~= nil then
       states[currentState]:update(dt)
    end
end

```

# Answer
> -1 votes
Well, though it's not pretty it's OK to handle states this way, IMO. You can make it much more cleaner using functions for each state, like:

```
if current_state == "game"
  game()
else if current_state == "titlescreen"
  titlescreen()

```

or something other bothers you in this approach (I mean except that Update method is very long)?

---
Tags: lua, architecture, love2d
---


# Question
Title: Procedural dungeon generation. No corridors, color key doors
I am curious how dungeons like the one in Runescape dungeoneering skill are generated. They basicaly have a 10x10 grid. So theres 100 rooms total. There's starting room and exit room. And each one are conected by open doors or doors that require key of some color. Anyone have idea how to generate something like this? I mean how to place doors and keys to make dungeon doable?

# Answer
> 10 votes
There are many different approaches to this. This also depends whether you always want to fill all your rooms or just a few of them.

Here's one possible approach **not** using all available rooms.

* Start with a random room, this is your entry point. Add this room to a list `open_ends`.
* Repeat the following steps till your dungeon is "complete" (e.g. target number of rooms achieved).
* Pick a random `open end` and a random direction.
* Remove the picked room from `open ends`.
* If the room you're "moving" to doesn't exist, create it and add it to `open ends`.
* Mark both rooms to have a connection between them, either unlocked or locked using one of the `available keys`.
* If you've picked a key and keys are one time use only, remove the key from `available keys`.
* If the room you're "moving" to doesn't have treasure, do a random roll to determine whether there is some.
* If there is treasure and it's a key (e.g. red key, blue key, etc.), add that key to `available keys`.

Now your dungeon is almost finished. You're still looking to get some stairs down or a boss room? Easy!

* Pick a random room from `open ends`.
* If there isn't one available, loop through all rooms and try to add a new one.
* Mark the room to be the boss room and remove it from `open ends`.

In a similar fashion, you can add stuff like treasure rooms, shops, libraries, temples, etc. as long as there's still room in your dungeon.

---

If you always want to use all available rooms, I'd probably use a different approach:

* For each room in your grid set random connections (e.g. left and right, up and right, etc.).
* Pick random rooms for your boss, treasure, etc.
* Set these random rooms to only have one entrance/connection.
* Use some pathfinding (Djikstra's?) algorithm to ensure the player is able to reach these rooms.
* If you add locked doors, make sure there's at least one path from the locked door to a key (mark it as "used") to the player's starting position. Once done, mark the door as "solved" (it can be passed in further iterations for other doors).

# Answer
> 1 votes
This kind of procedural generation is considered extensively at this website dedicated to listing game mechanic ideas. There are several entries on that site that go into quite a bit of detail on how procedural content generation can be done effectively. There are nearly 30 entries related to procedural generation. Reading these entries gave me a better understanding of procedural generation and helped me to fully appreciate what it is capable of.

This early entry seems the most relevant to your question. It details one method of accomplishing what you're asking.

---
Tags: mathematics, procedural-generation
---


# Question
Title: Android Game Development. Async Task. Loading Bitmap Images Sounds
Im working on this game for android.

And wanted to know if my thread architecture was right or wrong.

Basically, what is happening is, i am loading All the bitmaps,sounds etc in the initializevariables() method.

But sometimes the game crashes and sometimes it doesnt. So i decided to use async task. But that doesnt seem to work either (i too loads at times and crashes at times)

```
    @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setFullScreen();
    initializeVariables();

    new initVariables().execute();

//  setContentView(ourV);
}

private void setFullScreen()
{
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
}

private void initializeVariables()
{
    ourV=new OurView(this);
    stats = getSharedPreferences(filename, 0);

    ballPic  = BitmapFactory.decodeResource(getResources(), R.drawable.ball5);
    platform = BitmapFactory.decodeResource(getResources(), R.drawable.platform3);
    gameB    = BitmapFactory.decodeResource(getResources(), R.drawable.game_back2);
    waves    = BitmapFactory.decodeResource(getResources(), R.drawable.waves);
    play     = BitmapFactory.decodeResource(getResources(), R.drawable.play_icon);
    pause    = BitmapFactory.decodeResource(getResources(), R.drawable.pause_icon);
    platform2 = BitmapFactory.decodeResource(getResources(), R.drawable.platform4);

    countdown = BitmapFactory.decodeResource(getResources(), R.drawable.countdown);

    bubbles      = BitmapFactory.decodeResource(getResources(), R.drawable.waves_bubbles);

    backgroundMusic = MediaPlayer.create(this, R.raw.music);

    jump  =  MediaPlayer.create(this, R.raw.jump);
    click =  MediaPlayer.create(this, R.raw.jump_crack);

    sm  = (SensorManager) getSystemService(SENSOR_SERVICE);
    acc = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    sm.registerListener(this, acc, SensorManager.SENSOR_DELAY_GAME);
    ourV.setOnTouchListener(this);

    dialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
    dialog.setContentView(R.layout.pausescreen);
    dialog.hide();
    dialog.setOnDismissListener(this);

    resume = (Button) dialog.findViewById(R.id.bContinue);
    menu   = (Button) dialog.findViewById(R.id.bMainMenu);
    newTry = (Button) dialog.findViewById(R.id.bNewTry);

    tv_time = (TextView) dialog.findViewById(R.id.tv_time);
    tv_day  = (TextView) dialog.findViewById(R.id.tv_day);
    tv_date  = (TextView) dialog.findViewById(R.id.tv_date);

    resume.setOnClickListener(this);
    menu.setOnClickListener(this);
    newTry.setOnClickListener(this);

}

    @Override
protected void onResume()
{
    //if its running the first time it goes in the brackets
    if(firstStart)
    {
        ourV.onResume();
        firstStart=false;
    }
}

```

Now what onResume in ourV does is , its responsible for starting the thread

```
            //this is ourV.onResume
        public void onResume()
        {
            t=new Thread(this);
            isRunning=true;
            t.start();
        }

```

Now what I want is to initialise all bitmaps sounds etc in the async background method

```
    public class initVariables extends AsyncTask<Void, Integer, Void>
            {

                ProgressDialog pd;

                @Override
                protected void onPreExecute()
                {
                    pd = new ProgressDialog(GameActivity.this);

                    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    pd.setMax(100);
                    pd.show();
                }

                @Override
                protected Void doInBackground(Void... arg0)
                {

                    synchronized (this)
                    {

                    for(int i=0;i<20;i++)
                    {
                        publishProgress(5);

                        try {
                            Thread.sleep(89);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    }

                    return null;
                }

                @Override
                protected void onProgressUpdate(Integer... values)
                {
                    pd.incrementProgressBy(values[0]);
                }

                @Override
                protected void onPostExecute(Void result)
                {
                    pd.dismiss();

                    setContentView(ourV);
                }

            }

```

Now since I am new to this. You could tellme maybe if async is not required for such stuff and there is another way of doing it normally.

# Answer
> 1 votes
You aren't doing any initialization within your AsyncTask. You basically just sleep and update a ProgressDialog. But what you should do, is to put most of the code from within your `initializeVariables()` method into your `doInBackGround()` method.

The way you are doing it, you are still using the main thread for all time-consuming tasks.

---
Tags: android, loading
---


title: Detect collision in Blender

text:
# Question
Title: Detect collision in Blender
I am trying to write a Python function for Blender(2.66) game engine, that permits me to detect collision between two objects.

I tried to read the documentation, but it's very confusing, and I don't understand it.

Someone have an example how to do it?

# Answer
> 1 votes
Very good tutorial here for character creation:

Part 1: http://www.youtube.com/watch?v=DBdpIDGXEPU

Part 2: http://www.youtube.com/watch?v=oTI1A\_FzOB8

Part two at 12:40 the lesson moves to collisions.

I am not a python expert but when you hover over any buttons in blender it shows the name of the python reference for it. When I tested a collision sensor it popped up with

```
Python: CollisionSensor.type bpy.data.objects["Cube"]

```

bpy is blender python the blender related code package.

There is also an interactive python display above the info panel (cant remember if it was introduced in the 2.6 series or not) which shows the python code which would do whatever activity you just did with the GUI.

---
Tags: collision-detection, blender, python, blender-game-engine
---


# Question
Title: Random/Procedural vs. Previously Made Level Generation
What the advantages/disadvantages of using random/procedural generation vs. pre-made levels?

There seems to be few that I can think of, other than the fact that items may be a problem to distribute in randomly generated terrain, and that the generated terrain may look weird.

The downside to previously made levels is that I would need to make a level editor, though. I cannot decide what is better to use.

Could answers include code/examples of both procedural and premade generation, as well as the pros/cons?

# Answer
To briefly answer your main question first, the main **advantages** of a procedurally generated game world are that:

* The world can be *huge*, much larger than any manually designed game world could possibly be.
* The world (or at least parts of it) can be regenerated for each game, potentially increasing replay value, since the player will always have something new to discover.

Conversely, the main **disadvantages** of procedural generation are that:

* Depending on the generation methods used, it can be hard to make sure that the world is always playable, i.e. that the player can't get stuck with no way to proceed just because they gut unlucky with the world generation.
* Even if you can avoid generating completely unplayable worlds, random world generation can lead to a highly variable difficulty level: sometimes, the player might find everything they need just conveniently lined up for the taking, sometimes they might go a long time without finding anything useful.

Over long periods, such random fluctuations do tend to average out, but if the game difficulty is e.g. heavily front-loaded (typical for survival games), a bad start could ruin a game while a very lucky start could rob it of all challenge.
* Poorly done procedural generation can make the world feel monotone and boring: after you've seen a dozen randomly generated mazes, they all start to look the same, even if they differ in details.
* Also, if the game world is *completely* regenerated for each game, there will be no fixed locations or features that the player could recognize from previous games. Such lack of familiarity could make it harder for the player to engage with the game on an emotional level, or to share experiences with other players.

There's also one thing that you could count in either list: in a game where the world is randomly regenerated for each game, there can be no such thing as a "walkthrough" guide, since every playthrough will be different.

(This unrepeatability could also be a problem for testing and debugging, although it can be at least partially avoided by allowing the RNG seed to be specified, at least in debug mode, and/or by providing "cheat" command that can be used to fast-forward play to different stages.)

---

However, if you look at the disadvantages list, you'll see that it mostly describes the disadvantages of *pure* procedural generation; a lot of them can be avoided by **mixing manually and procedurally generated content**.

For example, the player could always start in fixed, manually designed town, perhaps surrounded by a wider more or less fixed home region, but places further away from town could be randomly generated to always provide unfamiliar regions for the player to explore.

There could also be other manually designed towns or other locations placed (more or less) randomly in the world, such that the player will have to find them, but will know what to expect once they get there. Conversely, prominent features such as mountains could be manually placed (at least in the vicinity of the fixed starting location), but the details of their terrain could be randomized.

As for random placement causing deadlocks and difficulty variation, that can be addressed by implementing various consistency and balance checks on top of your procedural world generation algorithm. For example, if the player needs a particular item to be able to cross water, you could include some code making sure that at least one such item is placed so that the player can reach it without crossing water.

Similarly, you might also want to tweak your item placement rules so that no *wands of balance-breaking awesomeness* are placed before the player has reached level *x*, and maybe to ensure that at least one is placed in a fixed location where the player can reach it before getting to the stage where they're going to need it to survive.

---

By the way, a common way to make procedural and manually generated content mesh more or less seamlessly is to start the manual generation process by using the procedural world generator (maybe suitably tweaked, e.g. to generate a village or a mountain peak where you want it) to initialize the region you're designing, and then manually tweaking it to add and adjust the details you want. (This can also allow very compact level storage, by only saving the manual changes and the generator seed and parameters used.)

Other ways to combine manual and procedural content include leaving blank spots in your manually designed levels, to be filled in by randomized content (e.g. a castle could include a randomly generated maze in the dungeons, with only the outline and the exits fixed), or the manual design could specify only the broad outline of some parts of the level (e.g. the placement of houses in a town) and leave the details (such as the exact appearance of each house) to be picked randomly.

In fact, even many games that have entirely fixed game world use *some* form of procedural generation as part of their level design process, since there are some aspects of world generation (like producing natural-looking terrain, or placing individual trees in a forest) that are difficult and/or tedious to do by hand, but relatively easy to automate.

Conversely, most procedural world generators will use at least *some* manually designed objects and elements to build the world out of. One could even easily have multiple levels of nested random / manual generation: for example, a procedurally generated world could include a manually generated town surrounded by procedurally generated woods with a manually drawn outline, with procedurally generated trees bearing manually designed leaves.

---

Also note that procedural content generation isn't necessarily incompatible with a fixed world: you could just pick a fixed RNG seed and use it to generate your world. This can be useful if you want a huge world for the players to explore, but want to keep it the same for every game and every player.

Note that, if you do this (or possibly even if you don't), you really should design your world generator to work in a hierarchical fashion, using multiple RNG instances, such that e.g. the overall map generator would keep a single RNG instance that it would use to generate subregions, assigning to each subregion a different seed value that the region generator would then use to seed a separate RNG instance that it'd use to generate the region, and so on. This is to avoid the "butterfly effect", where changing even the tiniest detail of the tiniest part of the map could throw the RNG out of sync and cause everything else in the world to be completely different.

Another important way to avoid the butterfly effect, particularly if you're generating the world "on the fly" as the player explores it, is to avoid normal RNGs entirely (except for processes that happen "instantaneously" from the player's viewpoint, like generating a new level when the player enters it) and instead use random number generation methods that don't store any internal state. For example, when choosing the seed for a subregion the player is about to enter, the overall world generator could take the coordinates of the subregion (and its own overall seed) and feed them to a hash function to generate the subregion seed. That way, each region will always look the same, regardless of the order in which the player enters them.

---

Ps. After all that digression, let me briefly address your final question about the actual code used for procedural generation. Alas, I don't think it's really answerable in any meaningful sense without a *lot* more detail than you've provided, since there are literally as many different ways to do procedural world generation as there are games using them.

For example, the great grand-daddy of all procedurally generated exploration games is probably Rogue, whose level generation algorithm simply consisted of randomly placing a bunch of rectangular rooms within a larger rectangular level, and connecting those rooms with passages (and placing a staircase to the next level in one of them). Its diverse successors, from Nethack to the Diablo series, have elaborated on this system in many ways, but most have retained the basic idea of distinct levels consisting of rooms, dungeons and mazes more or less randomly placed on a grid map.

Conversely, for games featuring open outdoor settings, you'll probably want to start with some kind of fractal terrain generation algorithm and build other features (rivers, forests, towns, etc.) on top of that. Or you could do something like what Minecraft does, and generate a random 3D procedural texture determining which parts of your landscape are ground and air respectively (scaled and biased so that lower blocks are more likely to be ground), and then overlay features like water, soil/rock, vegetation, etc. on top of it.

Of course, none of the above applies if you're, say, writing a game of *space* exploration, in which case you'll just need to generate a bunch of randomly placed star systems according to some density function, and then generate a random set of stars and planets in each of them. Or maybe you're setting you players to explore a non-Euclidean landscape, in which case you'll be facing a completely different set of challenges (such as the fact that the volume within a given radius grows exponentially rather than polynomially, making it *really* hard to keep a large map in memory).
> 26 votes

# Answer
**Advantages of Procedural Generation**

1. Can easily scale your maps / designs to truly large sizes, much larger than you could create by hand.
2. By creating a system where chunks of terrain are created on the fly, you can avoid having to write pieces of code to load in chunks from permanent memory.
3. Over the long term, you may be able to discover more viable levels using procedural design than with manual map editing.
4. For your 'explorer' game, you can generate many dozens, hundreds or even thousands of levels that are different to one another which keeps the player from getting bored.

**Disadvantages of Procedural Generation**

1. Requires much work to ensure that generated terrain looks 'how you want it to'.
2. Creating 'test levels' becomes a hassle.
3. Placement of items and other such things, as you mentioned, must be done carefully, though for a top down explorer game this would probably be less of an issue than you think.
4. Unless extensive testing is done, you may get a scenario where your gameplay breaks completely with a particular procedural level, more so than if you made a level by hand.
5. For truly complex terrains, you may end up spending more time on bug fixing and design work then you would have spent making a basic map design tool and file loader.

**Advantages of Manual Design**

1. The game designer can be more assured that gameplay functions as it should within the context of each level.
2. It is possible to create and place 'fine details' more easily then you can with procedural generation.
3. Some terrain features are very difficult to produce procedurally, such as water that flows down a mountain. Doing so would require very thorough evaluation of an elevation map which may be difficult to design.
4. Easier to guide the player along a 'linear path', though as you say you are building an 'explorer' game, this may not be so relevant.

**Disadvantages of Manual Design**

1. Applying widespread changes to your terrain will be time consuming, whereas with procedural generation, merely the modification of a few values will yield completely different terrain.
2. You will have to store each map in memory, which might be acceptable for small levels, but for larger levels, procedural generation might be your only option. Increases the permanent memory installation requirements of your game.
3. May require the construction of a map editor and file loading system.

I've ended up listing more disadvantages for procedural content generation, though this is probably because my project is entirely procedural so I know its pitfalls. For an explorer game, I would advise you to consider how large you want each map to be and whether creating separate map editing tools is something you're willing to do.
> 7 votes

---
Tags: game-design, algorithm, procedural-generation, level-design, levels
---


title: Why Android for new (micro) consoles?

text:
# Question
Title: Why Android for new (micro) consoles?
There are a lot of new (micro) consoles with Android inside coming soon or already there (OUYA for example).

My question is: why use Android and not another OS as base for these consoles?

I assume that there are pragmatic answers to this but I can't see any clear killer feature. For example, one can assume that any stable Linux distribution would work (like Valve seem to think). Android is primarily targetted at mobile platforms which mean it is built around the idea of being interrupted which goes against a lot of what console devs needs in new hardware - but is not killing Android as a platform for gamedev either as it's just a constraint.

Why not another OS? What's the Android killer features that make micro-console builder using it instead of Linux or anything else?

# Answer
> 3 votes
I'm not a professional in the console world, but I have some theories on why a company might choose Android over a different OS or creating a new OS for their console.

* **Name Brand recognition.** Consumers with no knowledge of OSes will be confident that the device they're buying is running on something that's popular enough to be on their smartphone and millions of others.
* **Developing an entirely new OS would add significant upfront and sustaining costs to the development of the console.** Developing a new OS like Android is something very large companies with loads of cash do, like Google, Sony or Microsoft. Getting into the console market isn't easy or cheap. Using existing technology where available is an excellent way to reduce costs.
* **Android is a platform that many developers are familiar with already.** No one is going to buy a console if there aren't any games for it. While mainstream consoles like XBox and Playstation have large companies developing games for them, the future of the micro console appears to be the indie developer. Indie developers run on shoestring budgets and tight timelines. They don't have time to learn entirely new OSes. The console developers need the developers as much as the developers need a platform for their games. Using Android gives both a way to make that relationship easier to start.
* **Android *is* linux already**. Or a special version of it. So what are the alternatives? Microsoft or Apple would both cost far too much. Creating an entirely new OS is extremely expensive. So the alternative is to create another branch of Linux to use specifically for that console.

So what's the Android killer features that make it the OS of choice? Because it's there and it works. If it's not broken, don't fix it. If Android was placing significant restrictions on the developers to deploy the platform they want to deploy, then they'd use something else, so far, that doesn't seem to be the case.

(Valve would likely look at alternatives or creating their own to increase compatibility with *their* existing library of games).

---
Tags: android, console
---


# Question
Title: How to blend the sprite into background?
I try to blend the character into game but I still cannot remove the blue color in the sprite sheet and discover that the white area of sprite is semi-transparent.

Before that, the color `D3DCOLOR_XRGB(255, 255, 255)` is set in `D3DXCreateTextureFromFileEx`. You will see the fireball through the sprite.

After I change the color to `D3DCOLOR_XRGB(0, 255, 255)`, the result will be

Now, I am trying to remove the blue color of the sprite sheet and my expected result is something like that

Until now, I still cannot figure out how to do that. Any ideas?

```
void initPlayer()
{
    //  Create texture.
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "player.png", 169, 44,
         D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
         D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(0, 255, 255),
         NULL, NULL, &player);
}

void renderPlayer()
{
    sprite->Draw(player, &playerRect, NULL, &D3DXVECTOR3(playerDest.X, playerDest.Y, 0),D3DCOLOR_XRGB(255, 255, 255));
}

void initFireball()
{
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "fireball.png", 512, 512,
         D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
         D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
         NULL, NULL, &fireball);
}

void renderFireball()
{
    sprite->Draw(fireball, &fireballRect, NULL, &D3DXVECTOR3(fireballDest.X, fireballDest.Y, 0), D3DCOLOR_XRGB(255,255, 255));
}

```

# Answer
You have four options. First, edit the image and make the background transparent. This the "most correct" solution long-term.

Second, transform the background color on load before creating the texture. Loop over all pixels and set them to 0 alpha for the specified color. You may to alter the image format depending on how it's loaded.

Third, do this at runtime on the GPU. Load the image, bind a render target of the same size, then use a shader which alters the source pixels matching the background color. May or may not be faster than using the CPU.

Finally, worst option, just do this "on demand" with a shader and don't bother storing the results.
> 2 votes

# Answer
It has been a long time since I have used DirectX 9, but here is how I see it. You're going to want to, first:

1. Use an image editor of your choice to remove the blue section of the sprite directly so that it is transparent. This should be achievable with just about any program. Make sure you save as .png or another image format supporting transparency.
2. Use an image viewer to check that the sprite is now really transparent (windows default program will do).
3. Use a blend state of some sort in your rendering code to ensure that your alpha is not ignored.

For blend states, you might want to look into:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb172252(v=vs.85).aspx

On a cursory look I think D3DBLEND\_SRCCOLOR might be what you're looking for.
> 1 votes

---
Tags: directx, rendering, directx9
---


title: Setting Higher Z-Index for Sprite

text:
# Question
Title: Setting Higher Z-Index for Sprite
For my game, I have to set highest z index for my sprite. At present, I wrote following code but didn't work for me.

```
    Sprite houseSprite = new Sprite(pX, pY,
            textureManager.houseBgRegion.deepCopy(),
            mVertexBufferObjectManager);
    attachChild(houseSprite);
    houseSprite.setZIndex(500);
    sortChildren();

```

My requirement did not satisfied with setting sprite in the HUD. So any how I have to apply highest z index. Also in my game sprites are dynamically generated as per game play.

So members please share your thoughts.

# Answer
> 2 votes
You are either asking, how to set z-index in the scene higher than a z-index in the HUD, or how to set the highest z-index in the scene.

If it is the first option, bad news. There are three layers that have separate z-index. Background, the scene itself and HUD. Actually each Entity can be a layer with their own z-index. Background is always rendered first, then the scene and then HUD. If you set z-index to anything in the scene, HUD and its entities will always be rendered on top of it.

If you are interested in highest z-index in the current scene itself, after you sort the children by the zIndex, simply call

```
int max zIndex = getLastChild().getZIndex();

```

That child has the highest zIndex by definition.

---
Tags: libgdx, sprites
---


title: How object-oriented are videogames?

text:
# Question
Title: How object-oriented are videogames?
I've always wondered to what extent object orientation is used by videogames, especially huge 3D projects. I reckon it would be cool that both `troll` and `werewolf` inherited its attributes from `enemy` and overwrote some of them. But maybe classes are too heavy to be practical, I don't know...

# Answer
> 21 votes
To come to your example I will explain my thoughts about Entites in videogames. I won't discuss the general advantage and disadvantage of objects and classes, neither their whole role in Videogames.

Entities in small videogames are mostly defined by separate classes, in big games they are often defined in files. There are two general approaches to follow:

**Extension**: In your example `Troll` and `Werewolf` will extend `Enemy`, which extends `Entity`. `Entity` takes care about the basic things like movement, health etc., while `Enemy` would state the subclasses as enemies and do other things (Minecraft follows this approach).

**Component based**: The second approach (and my favorite) is one `Entity` class, which has components. A component could be `Moveable` or `Enemy`. These components take care of **one** thing like movement or physics. This method breaks long Extension chains and minimizes the risk of running into a conflict. For example: *How can you make non-moveable Enemies, if they inherit from a moveable Character?*.

In big videogames like World of Warcraft or Starcraft 2, Entities aren't classes, but sets of data, which specify the whole Entity. Scripting is also important, because you define what the Entity does not in a Class, but in a Script (if it is unique, not things like moving).

I am currently programming a RTS and I take the component based approach with Descriptor and Script files for Entites, Skills, Items and everything else dynamic in the game.

# Answer
> 26 votes
> I reckon it would be cool that both troll and werewolf inherited its attributes from enemy and overwrote some of them.

Unfortunately this approach to polymorphism, popular in the 90s, has shown itself to be a bad idea in practice. Imagine you add 'wolf' to the enemy list - well, it shares some attributes with werewolf, so you'd want to consolidate those into a shared base class, eg. 'WolfLike'. Now you add 'Human' to the enemy list, but werewolves are sometimes humans, so they share attributes too, such as walking on 2 legs, being able to talk, etc. Do you create a 'Humanoid' common base for humans and werewolves, and do you then have to stop werewolves deriving from WolfLike? Or do you multiply inherit from both - in which case, which attribute takes precedence when something in Humanoid clashes with something in WolfLike?

The problem is that trying and model the real world as a tree of classes is ineffective. Take any 3 things and you can probably find 4 different ways to factor their behaviour into shared and non-shared. This is why many have turned to a modular or component-based model instead, where an object is comprised of several smaller objects that make up the whole, and the smaller objects can be swapped or change to make up the behaviour you want. Here you might have just 1 Enemy class, and it contains sub-objects or components for how it walks (eg. Bipedal vs. Quadrupedal), its methods of attack (eg. bite, claw, weapon, fist), its skin (green for trolls, furry for werewolves and wolves), etc.

This is still completely object-oriented, but the notion of what is a useful object is different from what used to be commonly taught in the text books. Rather than having a large inheritance tree of various abstract classes and several concrete classes at the tips of the tree, you typically have just 1 concrete class representing an abstract concept (eg. 'enemy') but which contain more concrete classes representing more abstract concepts (eg. attacks, skin type). Sometimes these second classes can be best implemented via 1 level of inheritance (eg. a base Attack class and several derived classes for specific attacks) but the deep inheritance tree is gone.

> But maybe classes are too heavy to be practical, I don't know...

In most modern languages, classes aren't 'heavy'. They're just another way of writing code, and they usually just wrap the procedural approach you would have written anyway, except with easier syntax. But by all means, don't write a class where a function will do. Classes are not intrinsically better, only where they make the code easier to manage or to understand.

# Answer
> 8 votes
I'm not sure what you mean by "too heavy," but C++/OOP is the lingua franca of game development for the same good reasons that it is used elsewhere.

Talk of blowing caches is a design issue, not a language feature. C++ can't be too bad since it's been used in games for the past 15-20 years. Java can't be too bad since it's used in the very tight run time environments of smart phones.

Now on to the real question: for many years class hierarchies became deep and started to suffer from problems related to that. In more recent times class hierarchies have flattened and composition and other data-driven designs are being rather than logic-driven inheritance.

It's all OOP and still used as the baseline when designing new software, just different focus on what the classes embody.

# Answer
> 2 votes
Classes do not involve any run-time overhead. Run-time polymorphism is just calling through a function pointer. These overheads are exceedingly minimal compared to other costs like Draw calls, concurrency synchronization, disk I/O, kernel mode switches, poor memory locality, over-use of dynamic memory allocation, poor choice of algorithms, use of scripting languages, and the list goes on. There's a reason that object orientation has essentially supplanted what came before it, and it's because it's much better.

# Answer
> 1 votes
One thing to be aware of is that the concepts of object-oriented code are often more valuable than their implementation in languages. In particular, having to do 1000s of virtual update calls on entities in a main loop can cause a mess in the cache in C++ on platforms like 360 or PS3 - so the implementation might avoid "virtual" or even "class" keywords for the sake of speed.

Often though it will still follow the OO concepts of inheritance and encapsulation - just implementing them differently to how the language does itself (e.g. curiously recursive templates, composition instead of inheritance (the component based method described by Marco)). If the inheritance can always be resolved at compile-time then the performance issues go away, but the code can become a bit hairy with templates, custom RTTI implementations (again the built-in ones are usually impractically slow) or compile-time logic in macros etc.

In Objective-C for iOS/Mac there are similar, but worse problems with the messaging scheme (even with the fancy caching stuff)...

# Answer
> 0 votes
The method that I will be attempting to use mixes class inheritance and components. (First off, I don't make Enemy a class -- I make that a component.) I don't like the idea of using one generic Entity class for everything and then adding the necessary components to flesh the entity out. Instead, I prefer to have a class automatically add components (and default values) in the constructor. Then subclasses add their additional components in their constructor, so the subclass would have its components and its parent class components. For example, a Weapon class would add basic components common to all weapons, and then the Sword subclass would add any additional components specific for swords. I'm still debating about whether to use text/xml assets to define values for entities (or specific swords for example), or to do that all in code, or what the right mix is. This still allows the game to use the code language's type information and polymorphism, and makes ObjectFactories much simpler.

---
Tags: objects
---


# Question
Title: Packing jar files into library jar files
This question is not about packing a simple jar file (e.g. lwjgl) into a runnable jar file. I know how to do this using JarSplice. So if I have a game which uses JInput, I will pack my game jar and jinput.jar using JarSplice and enter the natives in the process. The problem arises when I want to create a custom library that uses JInput, and then pack that into my games. See, the whole idea of writing a game library is that I don't ever have to even copy code like the wrapper I wrote for JInput Controller, and I always have a definitive version inside a library jar. Basically what I want to do is create a jar file of my library, pack jinput.jar into it using JarSplice, possibly with the natives as well, and then when I want to export a jar of my game, I either export it automatically through Eclipse with the library jar, or, if that doesn't work, use JarSplice.

I've tried several solutions, and nothing works. When I try to pack the game jar and the library jar using JarSplice, I get an error saying that there's either duplicate .project or .classpath. When I try to export my game through Eclipse with the library jar, it won't run (which is to be expected), but then, if I try to attach the natives with JarSplice, it doesn't give me any errors but the jar doesn't run.

I'm not expecting anyone to solve this, but if anyone has an idea, something that will allow me to never look at the Gamepad code ever again, that would be awesome. I don't care if I have to package my library jar using JarSplice 5 times, and then do the same with the game jar, as long as it works. Otherwise I'll just have to copy the Gamepad class into every project alongside the library jar. :(

Edit: to clear things up, here's what I'm trying to do-
JInput has a class Controller, for controller input.
My\_Library has a class Gamepad, which is a wrapper for JInput's Controller.
My\_Game should be packed with My\_Library so that it can access My\_Library's different utilities, including Gamepad (for example, the class Player in My\_Game has a field Gamepad for the player to pass gamepad input).
If I can't pack them all into one fat jar, I guess it's OK, as long as I'll be able to place Gamepad in My\_Library and access it from My\_Game.

# Answer
Note that .jar files are simply .zip files with a different extension. You can freely view the contents and modify the archives with any zip program. Java also comes with a `jar` utility, which is a command-line program for creating, modifying and extracting .jar files. To make a .jar file executable, a manifest file is needed with `main-class` attribute. Learn to use these well. Don't be dependent on Eclipse creating your .jar files. Instead do it yourself from the command-line. Then make a script (either a shell script or Ant / Maven script), which does this for you. At least with Apache Ant manipulating .jar files is easy and combining multiple .jar files is simpler than from the command-line. Once you know how to work with .jar files well enough, you can offload the creation process to Eclipse or whatever tool you prefer, but only when you are the master and the tool is the slave.

One problem with executable .jar files is that the native binaries don't work inside them and must be present on the filesystem next to the .jar files. This is the point where you need JarSplice. It creates a wrapper class in the .jar file that first extracts the native files (e.g. lwjgl.dll) and then executes the original program. In addition it can create a native application such as .exe file for Windows. This means that JarSplice should be run only once and should be the last step when creating the distributable package. For intermediate libraries you should just combine the .jar files directly.
> 1 votes

---
Tags: java, lwjgl
---