# Question
Title: How are collision and collision callback systems usually implemented?
I'm writing my own game engine for learning purposes and was wondering about common ways to handle collision callbacks/responses. I'm NOT looking for ways to resolve collisions (no math needed here), I just want to know how systems are commonly set up to respond to one another.

For example, what I have designed now is a system where any entity, if they want to interact with the physical world, adds one of a few predefined shapes to the "physical objects list". One entity might want to add two squares to use as various bounding boxes, another entity might just add a circle as a collision area etc. Once every iteration, the collision detection system looks for collisions, and if it finds one, it checks the shape object's "parent" (the entity that added the shape) and notifies it of a collision and passes it a vector that can resolve it.

Even if someone can simply point me to an article that discusses this concept I would be grateful, as I haven't found any with some basic Google searches. (I also wouldn't know what to call this, collision callback is a term I made up, not sure if it makes sense).

# Answer
> 1 votes
Some engines, like Havok, let you implement your own handling.

Havok has 2 main types of collision bodies. For rigid bodies, Havok sends a callback for each unique collision point that happens. For "phantoms" which are convex shapes (or a list of convex shapes), you can listen for either per-point collision, or register for a broadphase AABB callback, which means you will get a callback any time something enters the smallest AABB that encompasses your other physics body. The system we setup at my last project for the per-point collision was each frame to create a collision map, when a collision occurred between two bodies, if those two bodies were already in the map then we skipped it, and by the end of the collision step we had a map of every object that was colliding with something, and what it had collided with. We kept the map from the previous frame, and by comparing last frame to this frame we know which collisions were new (occurred this frame but not last frame), and which collisions were no longer happening (occurred last frame but not this frame). Based on this we sent messages for new collisions, and collisions that had ended to each object that cared about collision checks.

JigLib and JigLibX have an almost identical system to Havok's in terms of sending collision points every frame (or every physics step).

Other physics engines likely do something similar to this. By doing things this way you have all the information you need for each collision contact, which can be used for other things than collision response events, but because you do have each contact event you have enough information to setup your own response system as well.

---
Tags: architecture, collision-resolution
---


# Question
Title: How can I determine which direction a 2D collision is occurring from?
The problem is as follows:

Think 2D Zelda (Links Awakening, A Link to the Past) style movement where you can run into walls from any of the four cardinal directions, or basically up, down, left, and right. The difference between my movement and these games is I want to allow for diagonal movement as well. When the player collides with a wall on the left, for example, if he is pushing left and up I want him to stop moving left but continue moving up. The problem I am having is my code currently detects the collision as both an upwards and a left collision so the player simply stops. What is the approach I should take to remedy this?

```
        bool canCollideLeft = false;
        bool canCollideRight = false;
        bool canCollideUp = false;
        bool canCollideDown = false;

        if (HeroRect.Left > OldHeroRect.Left)
        {
            canCollideLeft = false;
            canCollideRight = true;
        }

        if (HeroRect.Left < OldHeroRect.Left)
        {
            canCollideLeft = true;
            canCollideRight = false;
        }

        if (HeroRect.Bottom > OldHeroRect.Bottom)
        {
            canCollideUp = false;
            canCollideDown = true;
        }

        if (HeroRect.Bottom < OldHeroRect.Bottom)
        {
            canCollideUp = true;
            canCollideDown = false;
        }

        foreach (RectangleItemProperties rectangle in CollisionRectangles)
        {
            Rectangle CollisionRect = new Rectangle((int)rectangle.Position.X, (int)rectangle.Position.Y, (int)Math.Abs(rectangle.Width), (int)Math.Abs(rectangle.Height));

            if (HeroRect.Intersects(CollisionRect))
            {
                if (canCollideDown && HeroRect.Bottom >= CollisionRect.Top && HeroRect.Bottom <= CollisionRect.Bottom)
                {
                    hero.position.Y = OldHeroRect.Location.Y;
                }

                if (canCollideUp && HeroRect.Top >= CollisionRect.Top && HeroRect.Top <= CollisionRect.Bottom)
                {
                    hero.position.Y = OldHeroRect.Location.Y;
                }

                if (canCollideLeft && HeroRect.Left <= CollisionRect.Right && HeroRect.Left >= CollisionRect.Left)
                {
                    hero.position.X = OldHeroRect.Location.X ; ;
                }

                if (canCollideRight && HeroRect.Right >= CollisionRect.Left && HeroRect.Right <= CollisionRect.Right )
                {
                    hero.position.X = OldHeroRect.Location.X;
                }
            }
        }

```

In summary the code compares the old position with the new position to see which direction we have moved and checks for a potential collision there. So if we move up and to the left, canCollideLeft and canCollideUp will be true. I am pretty sure this is where my problem lies and I need to better check which direction I am colliding from.

Any thoughts or insight?

# Answer
From your code it seems you're checking both directions at the same time, but for proper movement it's better to check each direction individually. You can google around for Axis Aligned Bounding Boxes to find various methods of doing rectangle collision.
> 1 votes

---
Tags: collision-detection, movement, collision-resolution
---


# Question
Title: Are there any good tilesets for hex-based maps that are available for free use?
Does anyone know of any good tilesets for hex-based maps that are available for free use? The tiles from Battle for Wesnoth seem to be under a license that would allow others to use them in their games, but the game I'm developing is on a scale where a hex would be about equivalent to the area that a person would stand on, whereas the Wesnoth tiles are on a larger scale (for example, there are forest tiles with multiple trees on the hex). Are there any other games or other sources that have hex tile graphics available?

# Answer
OpenGameArt.org has several hex tile-sets.
> 4 votes

# Answer
Take a look at the Might and Magic Online game, it uses hexagon tiles but they are transparent.

I mean the playing ground is designed differently then the places where the hexagon tiles go.

Am I making any sense?

url for the game Might & Magic Online
> -1 votes

---
Tags: tiles, assets
---


title: Tweening Colors in OpenGL

text:
# Question
Title: Tweening Colors in OpenGL
I'm making a sky gradient in OpenGL by drawing with `glColorPointer` and `glDrawArrays`. I would like to be able to change the sky colour from morning to daytime to evening etc. I can either:

* Make a number of sprites and fade them in with my framework
* Somehow tween the color vector in openGL over time and use a single sprite

The second one seems like a more efficient option, but my framework doesn't pass the time delta into the draw method for me to decide how far I've progressed into fading.

Here's my current code:

```
glDisable(GL_BLEND);
glDisable(GL_DITHER);
glDisable(GL_FOG);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);

CGSize size = [[CCDirector sharedDirector] winSize];
float w = size.width;
float h = size.height;

const GLfloat vertices[] = {
    0, 0,
    w, 0,
    0, h/3,
    w, h/3,
    0, h*2/3,
    w, h*2/3,
    0, h,
    w, h,
};

const GLubyte colors[] = {
    254,255,134,255,
    254,255,134,255,
    230,157,0,255,
    230,157,0,255,
    230,60,0,255,
    230,60,0,255,
    167,0,86,255,
    167,0,86,255,
};

glVertexPointer(2, GL_FLOAT, 0, vertices);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 8);

glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);

glEnable(GL_TEXTURE_2D);

```

Which gives me:

# Answer
I fail to see what's the problem you're having. Update the time of day and tween the colors in the `Update` method (assuming it has access to the dt) and leave the `Draw` method *only* for rendering. I think that's the more logical solution. Also, encapsulate this in some sort of Sky class if you haven't done so already. So I'd definetly stick to the 2nd option. Something like:

```
class Sky
{
    void Update(float dt)
    {
        // Update timeOfDay based on dt
        // Update colors array based on timeOfDay
    }

    void Draw()
    {
        // Render sprite using current colors
    }

    float timeOfDay;
}

```

**Edit**

You wrote on the comments:

> The gradient I have defined above is split into sections, but I could conceivably split them into less or more, meaning I would complicate going from 4 colours to 3 colours etc.

So that's where the real problem lies. You should have been more clear about it instead of giving focus to the dt issue. In that case, you could consider using a fragment shader solution, but I think that the first option will be simpler to implement.

In particular, I think it would be a good idea to start by encapsulating the vertex/color generation code in a method that given a simple array of colors, would return the vertex/color arrays required for calling glVertexPointer and glColorPointer. Then use this method to generate each of the gradient sprites, and finally, given the `timeOfDay` determine which two of these sprites should be interpolated and by what amount. Then draw them on top of each other and interpolate the alpha value so that there's a cross-fade between them.

The alternative that would only require one sprite would be to do the gradient on a fragment shader. The first implementation that comes to my mind would be to pass it two 1D textures where each pixel corresponds to one of the colors of the gradient, along with an interpolation value between 0 and 1 to decide how much to fade between texture A and B. Then just render a single quad, and use the information above to calculate the color at each fragment. I'm not sure but you may also need to pass it either the width of the textures or how many colors there are in each of them in order to calculate the correct texture coordinates from which you should sample. There are probably other solutions though.
> 3 votes

---
Tags: opengl, tweening
---


title: Realistic metal shader

text:
# Question
Title: Realistic metal shader
How do you create a good metal shader?

For different metals and say more or less eroded / rusty and so on.

I know that one difference from ordinary materials is that metal should 'colour' the specular light but when I do that with gold for example it just looks "yellow", not metallic at all.

Any help appreciated!

# Answer
I have recently created shaders for both clean and brushed metals for my game in progress and I'm quite happy with the results.

**Clean metal:** The most important feature in my experiments was the environment reflections with cube maps. I implemented them with realtime render-to-texture environments, but also static images often gives good results and it's easier to blur them. The second most important feature was fresnel effect, which makes the silhuettes of the objects better. This for example gives a rounder look for balls. Specular lighting is not necessarily needed, as the cube map can provide the highlights directly. HDR rendering is also important to make the cube map reflections look good.

**Brushed metal:** For brushed metals you get good results quite easily by using a brush texture, something like this, together with anisotropic lighting. For anisotropic lighting you can find tutorials from the web, but I implemented my own by using blinn-phong as the base, but from the half-vector I eliminated 80% of the tangent direction. This means that you need tangents or bitangents in addition to normals in your models. The environment reflections are tricky for brushed metal. You can sample from multiple directions from the cube map based on the tangent/bitangent directions, but you might need lots of samples for good results. This however is not necessarily needed, as the texture and anisotropic lighting with multiple light sources already looks pretty nice. The end result in my case looks like this:
> 4 votes

# Answer
As Nicol said in his comment, there are a lot of things that go into a high-quality metal shader. For best results, your renderer needs to be gamma-correct and use physically-based shading models (see particularly the two papers by Naty Hoffman at that link).

Given those things, the typical way to make a metal material is to have a very low or nonexistent diffuse color and a high specular reflectance, ranging from 50% to 100% (in linear color space). As you noted, for some metals the specular will be colored.

Because the metal's appearance is entirely specular with little or no diffuse, reflection will be extremely important. If it only specularly reflects point lights, you will get the appearance of a black material since the rest of the environment is missing (even a very rough metal will reflect a blurred image of its surroundings). A typical way to get more reflection is to use a cubemap. Realistic reflection in real-time graphics is a huge topic, though, and there's a lot of different approaches out there.
> 6 votes

---
Tags: graphics, shaders, graphic-effects
---


title: Imports in python

text:
# Question
Title: Imports in python
Recently I downloaded a game off pydev and the imports for it look like this below.

```
import pygame
from pygame.locals import *

```

However I have only ever created games by calling the in this way.

```
import pygame
import player
import enemy
```

I have called in the class one by one.

What does the lines of code at the top do? does it call all of his classes in?

# Answer
It imports all public objects from `pygame.locals` into your module, so that you can use them directly instead of having to refer to them as `pygame.locals.whatever`.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: How can I represent and collide with interior boundaries in a maze?
I'm creating a 2D maze game in Python.

When I collide with the walls, the user can go through them but I want to be able to block him from doing that. How do I do this? Would I use an array?

I have created an outer wall before in another game, but that was just setting the bounds in the user class.

# Answer
> 2 votes
I assume from the picture you posted on StackOverflow that your world is tile-based, and you're after something like this. Then you can probably use the same data structure that you're already using for storing the map and rendering, when doing the collision detection in your game.

The first question I have to ask is, how does your character move - does it "teleport" between tiles, or does it move continuously in the world? The answer depends on that piece of information.

**Player Teleports between Tiles**

In the first case, it's extremely simple to deal with collisions. Whenever you're trying to move the character, just check if the block that he'll be moving into is a wall, and abort the move if that's the case.

**Player Moves Continously**

In the second case, it's a bit more complicated, but I already explained how to do this before in another question. There's a source code example in that answer, but it's written for C# and XNA so you'll have to adapt. The idea is language agnostic though:

1. Move character in one dimension (e.g. horizontally).
2. After the move, find all tiles that intersect the character's bounding box.
3. For each of them, detect collisions with walls and resolve them by moving the player back by the penetration amount.
4. Repeat the process for the other dimension (e.g. vertically).

*Note: I found that doing this process separatedly for horizontal and vertical movement helped guard against a series of edge case problems, hence my suggestion.*

# Answer
> 0 votes
I think that this is not only Python specific problem. You can create some bounding boxes around walls and than compute collisions with them = if user collide, shift him outside the box.

You can also use some kind of 2D array (texture with information, where user can go and where not).

---
Tags: collision-detection
---


# Question
Title: Implementing behavior in a simple adventure game
I've been entertaining myself lately by programming a simple text-based adventure game, and I'm stuck on what seems like a very simple design issue.

To give a brief overview: the game is broken down into `Room` objects. Each `Room` has a list of `Entity` objects that are in that room. Each `Entity` has an event state, which is a simple string-\>boolean map, and an action list, which is a string-\>function map.

User input takes the form `[action] [entity]`. The `Room` uses the entity name to return the appropriate `Entity` object, which then uses the action name to find the correct function, and executes it.

To generate the room description, each `Room` object displays its own description string, then appends the description strings of every `Entity`. The `Entity` description may change based on its state ("The door is open", "The door is closed", "The door is locked", etc).

Here's the problem: using this method, the number of description and action functions I need to implement quickly gets out of hand. My starting room alone has about 20 functions between 5 entities.

I can combine all actions into a single function and if-else/switch through them, but that's still two functions per entity. I can also create specific `Entity` sub-classes for common/generic objects like doors and keys, but that only gets me so far.

EDIT 1: As requested, pseudo-code examples of these action functions.

```
string outsideDungeonBushesSearch(currentRoom, thisEntity, player)
    if thisEntity["is_searched"] then
        return "There was nothing more in the bushes."
    else
        thisEntity["is_searched"] := true
        currentRoom.setEntity("dungeonDoorKey")
        return "You found a key in the bushes."
    end if

string dungeonDoorKeyUse(currentRoom, thisEntity, player)
    if getEntity("outsideDungeonDoor")["is_locked"] then
        getEntity("outsideDungeonDoor")["is_locked"] := false
        return "You unlocked the door."
    else
        return "The door is already unlocked."
    end if

```

Description functions act in pretty much the same way, checking state and returning the appropriate string.

EDIT 2: Revised my question wording. Assume that there may be a significant number of in-game objects that don't share common behavior (state-based responses to specific actions) with other objects. Is there a way I can define these unique behaviors in a cleaner, more maintainable way than writing a custom function for each entity-specific action?

# Answer
> 5 votes
Rather than making a separate function for every combination of nouns and verbs, you should setup an architecture where there is one common interface that all the objects in the game implement.

One approach off the top of my head would be to define an Entity object that all the specific objects in your game extend. Each Entity will have a table (whatever data structure your language uses for associative arrays) that associates different actions with different results. The actions in the table will likely be Strings (eg. "open") while the associated result could even be a private function in the object if your language supports first-class functions.

Similarly, the state of the object is stored in various fields of the object. So for example, you can have an array of stuff in a Bush, and then the function associated with "search" will act on that array, either returning the object found or the string "There was nothing more in the bushes."

Meanwhile, one of the public methods is something like Entity.actOn(String action) Then in that method compare the action passed in with the table of actions for that object; if that action is in the table then return the result.

Now all the different functions needed for each object will be contained within the object, making it easy to repeat that object in other rooms (eg. instantiate the Door object in every room that has a door)

Finally, define all the rooms in XML or JSON or whatever so that you can have lots of unique rooms without needing to write separate code for every single room. Load this data file when the game starts, and parse the data to instantiate the objects that populate your game. Something like:

```
<rooms>
  <room id="room1">
    <description>Outside the dungeon you see some bushes and a heavy door over the entrance.</description>
    <entities>
      <bush>
        <description>The bushes are thick and leafy.</description>
        <contains>
          <key />
        </contains>
      </bush>
      <door connection="room2" isLocked="true">
        <description>It's an oak door with stout iron clasps.</description>
      </door>
    </entities>
  </room>

  <room id="room2">
    etc.

```

---

ADDITION: aha, I just read FxIII's answer and this bit near the end jumped out at me:

```
(no things like <item triggerFlamesOnPicking="true"> that you will use just once)

```

Although I disagree that a flame trap being triggered is something that would only happen once (I could see this trap being reused for many different objects) I think I finally get what you meant about entities that react uniquely to user input. I would probably address stuff like making one door in your dungeon have a fireball trap by building all my entities with a component architecture (explained in detail elsewhere).

This way each Door entity is constructed as a bundle of components, and I can flexibly mix-and-match components between different entities. For example, the majority of the doors would have configurations something like

```
<entity name="door">
  <description>It's an oak door with stout iron clasps.</description>
  <components>
    <lock isLocked="true" />
    <portal connection="room2" />
  </components>
</entity>

```

but the one door with a fireball trap would be

```
<entity name="door">
  <description>There are strange runes etched into the wood.</description>
  <components>
    <lock isLocked="true" />
    <portal connection="room7" />
    <fireballTrap />
  </components>
</entity>

```

and then the only unique code I would have to write for that door is the FireballTrap component. It would use the same Lock and Portal components as all the other doors, and if I later decided to use the FireballTrap on a treasure chest or something that's as simple as adding the FireballTrap component to that chest.

Whether or not you define all the components in the compiled code or in a separate scripting language isn't a big distinction in my mind (either way you are gonna be writing the code *somewhere*) but the important thing is that you can significantly reduce the amount of unique code you need to write. Heck, if you aren't concerned about flexibility for level designers/modders (you are writing this game by yourself after all) you could even make all the entities inherit from Entity and add components in the constructor rather than a config file or script or whatever:

```
Door extends Entity {
  public Door() {
    addComponent(new LockComponent());
    addComponent(new PortalComponent());
  }
}

TrappedDoor extends Entity {
  public TrappedDoor() {
    addComponent(new LockComponent());
    addComponent(new PortalComponent());
    addComponent(new FireballTrap());
  }
}

```

# Answer
> 1 votes
The dimensional problem you address is quite normal and nearly unavoidable. You want to find a way to express your entities that is both *coincise* and *flexible*.

A "container" (the bush in the jhocking answer) is a *coincise* way but you see that is not *flexible* enough.

I do not suggest you to try to find a generic interface and then use configuration files to specify the behaviours, because you will always have the *unpleasant sensation* to be **between a rock**(standard and boring entities, easy to describe) **and a hard place** (unique fantastic entities but too long to implement).

My suggestion is to **use** an **interpreted language** to code behaviours.

Think about the bush example: it is a container but our bush need to have specific items within; the container object may have:

* a method for the storyteller to add item,
* a method for the engine to show the item it contains,
* a method for the player to pick an item.

One of theese items has a rope that trigger a contraption that in turn fires a flame burning the bush... (you see, I can read your mind so I know the stuffs you like).

You can use a *script to describe this bush* instead of a config file putting the relevant extra code in a **hook you execute** from your main program **each time someone picks an item** from a container.

Now you have a lot of architecture choices: you can define behavioral tools as base classes using your code language or the scripting language (things such containers, door-like and so on). The *purpose* of theese things is to let you to *describe the entities easely aggregating simple behaviours* and *configuring them using bindings on a scripting language*.

All the entities should be accessible to the script: you may associate an identifier to each entity and put them in a container that is exported in the extend of the scripting language script.

Using scripting strategies let you to keep your configuration simple (no things like `<item triggerFlamesOnPicking="true">` that you will use just once) while letting you to express odd beaviours(the fun ones) adding some line of code

In few words: scripts as config file that can run code.

---
Tags: architecture, software-engineering, text-based, behavior
---


# Question
Title: How do I avoid causing more collisions, when resolving multiple AABB collisions?
I have a lot of AABB bouncing on the screen. Doing collision/response between 2 AABB is fairly easy, but how do you handle this when you can be pulling AABB's apart but making them getting into another AABB? I mean something like this scenario:

1. We have 3 AABBs.
2. We check if first one collides with the other two. No collision is found.
3. We check if second collides agains the third (we don't need to recheck agains first). We find a collision, we separate second AABB form third but it intersects now with first one.

This will produce a bad response/collision detection. How do you handle this chained collisions?

Edit: I forgot to say that all aabb are dynamics objects. I mean, they move.

# Answer
Most physics engines that I have seen/used solves this problem by apply a force to the objects instead of directly changing the positions. This does it so that we only need to check collisions once between each object(or not even that if one is using culling algorithms) per update.

e.g. if you only have circles you simply give colliding objects a force away from the centre that is scaled to how close the other object is. AABBs is also somewhat simple as long as you don't need to rotate them. When I implemented a simple physics system(although we used OBBs but we still didn't care about angular velocity) we pushed the objects in the direction of its the closest edge.
> 5 votes

---
Tags: collision-resolution, aabb
---


title: Stuck at enemy movement

text:
# Question
Title: Stuck at enemy movement
I am making a TD game in unity, Initially I made all of my enemy movements frame rate dependent say:

I had a grid point1 at -22.65 and other at -21.1, diagrammatically:

(-22.65) ***_*\__*_*\__*_*\__**(-21.1)***_*\__*_*\__*_***(-21.1+1.55) ......

so the distance on x axis between two points is 1.55, divided it by 25 jumps with each enemy jump of 0.062 of each frame. On reaching on next point of grid the enemy find again its path. All went fine until I have requirement of FastForward and Pause feature. I used timeScale property of unity but it wont work as they are frame dependent. I also tried double speed of enemy on clicking fast forward button at any time, it has some issues that enemy jumps are now less and it fails to reach on next grid point.

Could someone suggest me solution to my problem. Do I need to change the enemy movement code to make it frame independent ?? I need the enemy to reach on the grid specific point I also need later to slow down any one enemy's speed when tower fires on it. Thnx

# Answer
> 1 votes
If you are using fixedUpdate() then could change the fixedDeltaTime. Otherwise if it's in the update() function then the movement should use the delta time so you could use the timeScale property you mentioned.

---
Tags: game-design, unity, timing
---


# Question
Title: How to organize a game engine in C++? Is my use of inheritance a good idea?
I'm a beginner both in game developping and programming.

I'm trying to learn some principle in the building of a game engine.
I want to create a simple game, I'm at the point where I'm trying to implement the game engine.

So I thought my game engine should control this things:

```
- Moving the objects in the scene
- Checking the collisions
- Adjusting movements based on collisions
- Passing the polygons to the rendering engine

```

I designed my objects like this:

```
class GlObject{
private:
    idEnum ObjId;
    //other identifiers
public:
    void move_obj(); //the movements are the same for all the objects (nextpos = pos + vel)
    void rotate_obj(); //rotations are the same for every objects too
    virtual Polygon generate_mesh() = 0; // the polygons are different
}

```

and I have 4 different objects in my game: plane, obstacle, player, bullet and I designed them like this:

```
class Player : public GlObject{
private:
    std::string name;
public:
    Player();
    Bullet fire() const; //this method is unique to the class player
    void generate_mesh();
}

```

Now in the game engine I want to have a general object list where I can check for example for collision, move objects, and so on, but I want also that the game engine will take the user commands to control the player...

Is this a good Idea?

```
class GameEngine{
private:
    std::vector<GlObject*> objects; //an array containg all the object present
    Player* hPlayer; //hPlayer is to be read as human player, and is a pointer to hold the reference to an object inside the array
public:
    GameEngine();
    //other stuff
}

```

the GameEngine constructor will be like this:

```
GameEngine::GameEngine(){
    hPlayer = new Player;
    objects.push_back(hPlayer);
}

```

The fact that I'm using a pointer is because I need to call the `fire()` that is unique to the Player object.

So my question is: is it a good idea? Is my use of inheritance wrong here?

# Answer
For the logics data and functions of your game objects (entities) I would strongly recommend using composition over inheritance. A good start would be the component based approach. It is well described in this Cowboy Programming article which describes how this architecture can be implemented and how it benefited the Tony Hawk franchise.

Also this article about entity systems inspired me when I first read it.

Inheritance is a great tool for polymorphism. Excepting for very simple projects you should avoid using it as a way to structure the entities and your game logics. If you go with inheritance you will most certainly end-up with having to replicate and maintain copies of the same code to implement functions that cannot be inherited from a common parent. And you will probably start polluting your classes with logics and data most commonly used to avoid replicating too much code.

Components are very handy in numerous situations. You can achieve much more using them :

**Flexibility with your entity types**: There are times in game development where some entities evolve suddenly and while the game designer makes the decision de developer will have to implement it. It takes just a few steps to add an existing behavior without replicating code. Component based systems allow more changes to be done by non programmers. For example each type of entity instead of being represented by a class can be represented by a description file which contains all the component names and parameters needed to configure the type. This allows non programmers to do and test changes without recompiling the game. Simply editing the description files will be enough to add, remove or change the components used by each entity type.

**Flexibility with particular instances and specific scenarios**: There are cases where you need your player to be able to equip weapons, or items, you can add an inventory component to your player. during the development of your game you will need other entities to have an inventory (enemies for example). And at one point you have in your scenario a situation where a tree is supposed to contain some sort of hidden item. With components you can add an inventory component even to entities which type is not designed originally to have one with no additional programming effort.

**Flexibility at run time**: Components offer a very effective way to change the behavior of entities at runtime. You can add and remove components at runtime and thus create or remove behaviors and properties when needed. They also allow you to separate different types of data into groups that can (sometimes) be computed separately in parallel on multiple GPUs.

**Flexibility in time**: Components can be used to keep compatibility between versions. For example when changes are made between releases of a game you can (not always) simply add new components which implement the new behaviors and changes. Then the game will instantiate the right components attached to your entities depending on the save file loaded, peer connected or server the player joins. This comes extremely handy in scenarios where you can't control the release dates of the new version on all platforms (Steam, Mac App Store, iPhone, Android...).

For a better insight take a look at the \[component-based\] and \[entity-system\] tagged questions.
> 8 votes

# Answer
Depends on what you mean by 'good'. It will get the job done, certainly. It has plenty of up-sides, and down-sides. You won't find them until your engine is much more complex. See this question on SO, for discussion on the subject.

There's plenty of opinions either way, but if your engine code is still at that early stage, it will be hard to explain to you why it might be bad.

In general, Scott Meyers has some great things to say on inheritance. If you're still at that stage in development, read this book (Effective C++) before you continue. It's a fantastic book, and is a requirement for any coders working at our company. But to sum up the advice: if you are writing a class and considering using inheritance, be absolutely clear that the relationship between the class and its ancestor is an 'is a' relationship. That is, every B is an A. Don't just use inheritance as an easy way to give B access to functionality A provides, that way will lead to severe architectural problems, and there are other ways to do it.

Put simply; for an engine of any size, you will quickly find that the objects rarely fall into a neat hierarchical structure for which inheritance works. Use it when it's appropriate, but don't fall into the trap of using it for everything - learn other ways to inter-relate objects.
> 13 votes

# Answer
In general prefer composition to inheritance. http://www.artima.com/cppsource/codestandards3.html

Composition gives you more flexibility.
> 5 votes

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


title: Special Effects in a 3d game

text:
# Question
Title: Special Effects in a 3d game
I am creating a 3d game ( a car racing game) using opengl ES. i know the rendering concept and also using a physics engine for all the physics stuff. All modeling is done using 3d modeling softwares.

Now my question how to do the special effects within a game.

For example like when a car collides and toggle how to slow down all the environment effects which i saw in other available games. OR Nitrogen gas effects in a car race game.

Any suggestions will be of great help. I guess my question is clear, if not feel free to ask anything.

# Answer
> 3 votes
> how to slow down all the environment effects

This is usually done by scaling down the time. So 1 second in real time is like a 1/4 second in game time. On top of this there are appropriate sound effects, etc.

> Nitrogen gas effects in a car race game

This is a completely different effect. At its most basic level you can get by with just tightening the FOV and upping the motion blur.

---
Tags: 3d, animation, opengl-es
---


# Question
Title: Why is the background image less smooth on the phone?
I've just downloaded Gamestate code from create.msdn.com, and as you can see from the image below:

The result is less smooth then the image imported to visual studio, how do I increase the quality?

# Answer
Set

```
graphics.PreferredBackBufferFormat = SurfaceFormat.Color;

```

in your `Game` constructor. XNA sets the backbuffer to `SurfaceFormat.Bgr565` (16 bit) by default.
> 4 votes

# Answer
You should be able to get a better looking gradient by dithering the source image down to 565.

A quick search found this Photoshop plugin that will do it, and some instructions for doing it with ImageMagick.
> 2 votes

---
Tags: xna, image
---


# Question
Title: How do I generate a 3D race track from a spline?
I want to generate a 3-dimensional race track around a spline that describes its shape. Here's an illustrative video.

The track should be an endless tunnel that sweeps along a 3D spline, with some obstacles thrown in. My best idea so far has been to loft a circle shape along the spline.

I would also like some pointers into how to manage the geometry i.e. how to create it from the loft operation, manage its 'lifecycle' in memory, collision and texturing.

# Answer
I'm not sure what language you are working in but there is a procedural mesh extrusion example for Unity3D located here:

http://unity3d.com/support/resources/example-projects/procedural-examples

I'm sure you could look at the code and rework it for your situation.

EDIT: I'm working on a game that uses a procedural extruded rail system like the one you are starting but it's in C# in Unity3d. I'll give you an overview of how I create my rail extrusion based on a Cubic Bezier path so although the rail's mesh is procedurally generated, it's based on the Bezier path that I define ahead of time in an editor. It would be like a level editor in the case of your game, in my case, it's designing pinball tables. Listed below is an example of how I'm doing it:

1.) Build/Find and Implement a Bezier Path Class. This will give you the source data for your mesh extrusion. There is one in C# here that you can port to c++.

http://forum.unity3d.com/threads/32954-Waypoints-and-constant-variable-speed-problems?p=213942

2.) Once you have a Bezier Path created, data points from this path are sampled. This can be done via the Interp method on the class provided above. This will give you a list/array of Vector3 points along the Bezier path.

3.) Create a helper class to convert the Vector3 Bezier path data from step 2. In this case, I have a simple class called ExtrudedTrailSection as defined below:

```
public class ExtrudedTrailSection
{
    public Vector3 point;
    public Matrix4x4 matrix;
    public float time;

    public ExtrudedTrailSection() { }
}

```

4.) Iterate through your Vector3 sample data and convert to an array of ExtrudedTrailSections supplying it with the sample data and a base matrix that would be the root location of your extruded mesh.

5. ) Use the array of ExtrudedTrailSections to create an array of final Matrix4x4\[\] using the following code:

Matrix4x4 worldToLocal = rootTransform.worldToLocalMatrix;

```
    for (int i = 0; i < trailSections.Count; i++)
    {
            if (i == 0)
            {
                direction = trailSections[0].point - trailSections[1].point;
                rotation = Quaternion.LookRotation(direction, Vector3.up);
                previousRotation = rotation;
                finalSections[i] = worldToLocal * Matrix4x4.TRS(position, rotation, Vector3.one);
            }
            // all elements get the direction by looking up the next section
            else if (i != trailSections.Count - 1)
            {
                direction = trailSections[i].point - trailSections[i + 1].point;
                rotation = Quaternion.LookRotation(direction, Vector3.up);

                // When the angle of the rotation compared to the last segment is too high
                // smooth the rotation a little bit. Optimally we would smooth the entire sections array.
                if (Quaternion.Angle(previousRotation, rotation) > 20)
                    rotation = Quaternion.Slerp(previousRotation, rotation, 0.5f);

                previousRotation = rotation;
                finalSections[i] = worldToLocal * Matrix4x4.TRS(trailSections[i].point, rotation, Vector3.one);
            }
            // except the last one, which just copies the previous one
            else
            {
                finalSections[i] = finalSections[i - 1];
            }
        }

```

6.) Now you have an array of Matrix4x4\[\] and can extrude a mesh but first we need a reference mesh to extrude from. I have a utility class that will create a circular mesh face that we will supply to the mesh extrusion method.

```
public static List<Vector2> CreateCircle (double radius, int sides)
{
    List<Vector2> vectors = new List<Vector2> ();

    const float max = 2.0f * Mathf.PI;
    float step = max / sides;

    for (float theta = 0.0f; theta < max; theta += step) {
        vectors.Add (new Vector2 ((float)(radius * Mathf.Cos (theta)), (float)(radius * Mathf.Sin (theta))));
    }

    return vectors;
}

```

7.) Find the center of this data:

```
    public static Vector2 CalculateCentroid(List<Vector2> vectorList)
    {
        //////////////////////////////////////////////////////////////////////////
        // Local variables.
        float fArea = 0.0f, fDistance = 0.0f;
        Vector2 vCenter = Vector2.zero;
        int nIndex = 0, nLastPointIndex = vectorList.Count - 1;
        //
        //////////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////////
        // Run through the list of positions.
        for (int i = 0; i <= nLastPointIndex; ++i)
        {
            //////////////////////////////////////////////////////////////////////////
            // Cacluate index.
            nIndex = (i + 1) % (nLastPointIndex + 1);

            // Calculate distance.
            fDistance = vectorList[i].x * vectorList[nIndex].y - vectorList[nIndex].x * vectorList[i].y;

            // Acculmate area.
            fArea += fDistance;

            // Move center positions based on positions and distance.
            vCenter.x += (vectorList[i].x + vectorList[nIndex].x) * fDistance;
            vCenter.y += (vectorList[i].y + vectorList[nIndex].y) * fDistance;
        }
        //
        //////////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////////
        // Calculate the final center position.
        fArea *= 0.5f;
        vCenter.x *= 1.0f / (6.0f * fArea);
        vCenter.y *= 1.0f / (6.0f * fArea);
        //
        //////////////////////////////////////////////////////////////////////////

        return vCenter;
    }

```

8.) Now that we have the edge and center data for a radial face mesh, you can construct a mesh object using your data. The final vertex in the mesh is the center point we calculated. The final mesh is just a face that is supplied to the mesh extrusion method that I provided an example of in the Procedural mesh extrusion class of the Unity package. Again, this is my method and obviously you would have to feed this data into OpenGL. If you have a 3d utility library that you are using or can write your own mesh class, it would probably work better to generate your final extruded mesh as this data isn't really needed by opengl for rendering. This face mesh is just used as the reference for the mesh extrusion.

```
    List<Vector3> levelVerts = new List<Vector3>();
    List<Vector2> levelUVBary = new List<Vector2>();
    List<Vector2> levelUVs = new List<Vector2>();
    List<int> levelTris = new List<int>();

    int verticesPerNode = 4;
    int edgeCount = sourceMeshData.Count;

    List<Vector3> sourceVerts = new List<Vector3>();
    //Debug.Log("smd.c:" + sourceMeshData.Count);
    for (int i = 0; i < edgeCount; i++)
    {
        //Debug.Log("adding:"+levelShapeData[i].x+"/"+levelShapeData[i].y);
        sourceVerts.Add(new Vector3(sourceMeshData[i].x, sourceMeshData[i].y, 0));
        levelUVs.Add(new Vector2(0, 0));
        //sourceVerts.Add(new Vector3(levelShapeData[i].x, levelShapeData[i].y, modelLength / 2f));
    }

    sourceVerts.Add(new Vector3(sourceMeshCenter.x, sourceMeshCenter.y, 0));
    levelUVs.Add(new Vector2(0, 0));

    for (int i = 0; i < edgeCount - 1; i++)
    {                                       //0, 1, 2, 3
        levelTris.Add(sourceVerts.Count - 1); //4, 4, 4, 4
        levelTris.Add(i);                   //0, 1, 2,
        levelTris.Add(i + 1);               //1, 2, 3,
    }

    levelTris.Add(sourceVerts.Count - 1);
    levelTris.Add(edgeCount - 1);
    levelTris.Add(0);

```

9.) Find the outside edges of the circular mesh as needed by the mesh extrusion method. Again, this code is provided in the unity package.

```
public class Edge
{
    // The indiex to each vertex
    public int[]  vertexIndex = new int[2];
    // The index into the face.
    // (faceindex[0] == faceindex[1] means the edge connects to only one triangle)
    public int[]  faceIndex = new int[2];
}

public static Edge[] BuildManifoldEdges (Mesh mesh)
{
    // Build a edge list for all unique edges in the mesh
    Edge[] edges = BuildEdges(mesh.vertexCount, mesh.triangles);

    // We only want edges that connect to a single triangle
    ArrayList culledEdges = new ArrayList();
    foreach (Edge edge in edges)
    {
        if (edge.faceIndex[0] == edge.faceIndex[1])
        {
            culledEdges.Add(edge);
        }
    }

    return culledEdges.ToArray(typeof(Edge)) as Edge[];
}

```

10.) Feed all of this data into the Mesh Extrusion method..

```
public static void ExtrudeMesh (Mesh srcMesh, Mesh extrudedMesh, Matrix4x4[] extrusion, Edge[] edges, bool invertFaces)
{
    int extrudedVertexCount = edges.Length * 2 * extrusion.Length;
    int triIndicesPerStep = edges.Length * 6;
    int extrudedTriIndexCount = triIndicesPerStep * (extrusion.Length -1);

    Vector3[] inputVertices = srcMesh.vertices;
    Vector2[] inputUV = srcMesh.uv;
    int[] inputTriangles = srcMesh.triangles;

    //Debug.Log("inputUV:" + inputUV.Length);

    Vector3[] vertices = new Vector3[extrudedVertexCount + srcMesh.vertexCount * 2];
    Vector2[] uvs = new Vector2[vertices.Length];
    int[] triangles = new int[extrudedTriIndexCount + inputTriangles.Length * 2];

    // Build extruded vertices
    int v = 0;
    for (int i=0;i<extrusion.Length;i++)
    {
        Matrix4x4 matrix = extrusion[i];
        float vcoord = (float)i / (extrusion.Length -1);
        foreach (Edge e in edges)
        {
            //Debug.Log(e.vertexIndex.Length);
            vertices[v+0] = matrix.MultiplyPoint(inputVertices[e.vertexIndex[0]]);
            vertices[v+1] = matrix.MultiplyPoint(inputVertices[e.vertexIndex[1]]);

            uvs[v+0] = new Vector2 (inputUV[e.vertexIndex[0]].x, vcoord);
            uvs[v+1] = new Vector2 (inputUV[e.vertexIndex[1]].x, vcoord);

            v += 2;
        }
    }

    // Build cap vertices
    // * The bottom mesh we scale along it's negative extrusion direction. This way extruding a half sphere results in a capsule.
    for (int c=0;c<2;c++)
    {
        Matrix4x4 matrix = extrusion[c == 0 ? 0 : extrusion.Length-1];
        int firstCapVertex = c == 0 ? extrudedVertexCount : extrudedVertexCount + inputVertices.Length;
        for (int i=0;i<inputVertices.Length;i++)
        {
            vertices[firstCapVertex + i] = matrix.MultiplyPoint(inputVertices[i]);
            uvs[firstCapVertex + i] = inputUV[i];
        }
    }

    // Build extruded triangles
    for (int i=0;i<extrusion.Length-1;i++)
    {
        int baseVertexIndex = (edges.Length * 2) * i;
        int nextVertexIndex = (edges.Length * 2) * (i+1);
        for (int e=0;e<edges.Length;e++)
        {
            int triIndex = i * triIndicesPerStep + e * 6;

            triangles[triIndex + 0] = baseVertexIndex + e * 2;
            triangles[triIndex + 1] = nextVertexIndex  + e * 2;
            triangles[triIndex + 2] = baseVertexIndex + e * 2 + 1;
            triangles[triIndex + 3] = nextVertexIndex + e * 2;
            triangles[triIndex + 4] = nextVertexIndex + e * 2 + 1;
            triangles[triIndex + 5] = baseVertexIndex  + e * 2 + 1;
        }
    }

    // build cap triangles
    int triCount = inputTriangles.Length / 3;
    // Top
    {
        int firstCapVertex = extrudedVertexCount;
        int firstCapTriIndex = extrudedTriIndexCount;
        for (int i=0;i<triCount;i++)
        {
            triangles[i*3 + firstCapTriIndex + 0] = inputTriangles[i * 3 + 1] + firstCapVertex;
            triangles[i*3 + firstCapTriIndex + 1] = inputTriangles[i * 3 + 2] + firstCapVertex;
            triangles[i*3 + firstCapTriIndex + 2] = inputTriangles[i * 3 + 0] + firstCapVertex;
        }
    }

    // Bottom
    {
        int firstCapVertex = extrudedVertexCount + inputVertices.Length;
        int firstCapTriIndex = extrudedTriIndexCount + inputTriangles.Length;
        for (int i=0;i<triCount;i++)
        {
            triangles[i*3 + firstCapTriIndex + 0] = inputTriangles[i * 3 + 0] + firstCapVertex;
            triangles[i*3 + firstCapTriIndex + 1] = inputTriangles[i * 3 + 2] + firstCapVertex;
            triangles[i*3 + firstCapTriIndex + 2] = inputTriangles[i * 3 + 1] + firstCapVertex;
        }
    }

    if (invertFaces)
    {
        for (int i=0;i<triangles.Length/3;i++)
        {
            int temp = triangles[i*3 + 0];
            triangles[i*3 + 0] = triangles[i*3 + 1];
            triangles[i*3 + 1] = temp;
        }
    }

    extrudedMesh.vertices = vertices;
    extrudedMesh.uv = uvs;
    extrudedMesh.triangles = triangles;
}

```

The final output in my case looks like this..

Good luck, your game looks really cool! Let me know if you figure it out?

Chuck
> 5 votes

---
Tags: opengl, 3d, racing, procedural
---


# Question
Title: Implementing cheat safe loot algorithm at clientside
I am developing a "city building" type of browser based flash/flex game. I was checking some of the implementation of existing one of the popular games in facebook using decompilers. I noticed they have implemented the loot algorithm the client side and sending the loot item to the server which I think is not cheat safe.

Knowing the fact that there are cheaters every where and it is easy to manipulate the messages and send the best loot always, is there any way we can counter this type of cheats?

I dont have a concrete solution designed for it yet but I am thinking to track the drops by maintaining the loot history.

So instead of mere updating the resources/inventory, I will implement a logic which will compare the loot with history to see if the player is receiving the rare drops excessively and flag the user or take a smart decision (which I don't have yet)

Or

Is it a good idea to implement the loot algorithm in the server side? Since this is "city building" kind of game, where it will not have extensive user actions like in typical RPG games which can trigger loot events.

# Answer
I am going to play the devil's advocate here: but you should really be doing this on the server - even with this method you still need to have logic on the server which is arguably more complicated.

One way to is calculate metrics based on what the user has done. For example (e.g. let's say we were writing Diablo 1):

* In the last 10 minutes he has opened 2 chests and the maximum total gold worth from a chest at this level is 500g.
* Let's add 10% for some leniency/error.
* So he can't have gained more than 1100g.

Why did he gain 2000g worth of items? Clearly he is cheating. You could either decide on a suspend or a ban based on the percentage gain; or, you could find a curve that fits the users gold gain (before he cheated) and calculate how long it would have taken them to make that gold - and suspend the account until that time period lapses.

It becomes more involved though, some other questions your server needs to answer is:

* How did he loot when his character isn't near something that is lootable, or hasn't been looted already?
* Take into consideration any trading or alternate economic mechanism your game may have (e.g. loans, stock market, etc.)
* Any net loss - e.g. selling a broken item.

It becomes really complicated and running the simulation on your server will most likely result in better performance under load.
> 7 votes

# Answer
All multiplayer games that respect themselves takes all important decisions server side. All as in All. Never trust the client if there is something in an action that might give an advantage for the player.

World of Warcraft creates all loot, checks transactions etc server side but due to lag it lets the client control how the player moves (to check that out, just unplug the network when you are playing). They do of course check you don't move too fast for long times or teleport and so on.
> 11 votes

# Answer
If there is a risk of cheating which gives a given client an advantage over other players, then that specific part of the gameplay should be implemented on the server.

It does not need to be a resource hog, though. If you are worried about server load, you could take a **statistical approach**: randomly verify *eg.* 5% of the loot operations on the server. If at any moment there is a mismatch, ban the client. As long as the client cannot predict which of its operations is being verified, it will need to play fair all the time.
> 4 votes

# Answer
The main reason it's implemented in client side is to take the load from the server and share it between clients. You might not notice how much load it is to check every thing server side for 10 or even 100 clients but think about 10,000 clients in average. In these cases even a milisecond faster code in server might save lots of cash!

Besides normal clients ***don't*** decompile games, so as long as there is no cheat program or other stuff like that, there will be too few cheaters and therefore companies can find them easily.

I've known some games which check thing server-side for example there is a game named runescape which almost does everything server-side. I remember once they were boasting about doing all pathfinding server side, and it resulted in much more smooth movement. before that one might set direction, move a little bit toward a direction and then move the other way due to delay in server response. I'm not sure but I think WoW use same system (for NPC and loots) as well.
> 0 votes

---
Tags: game-design, browser-based-games, security
---


# Question
Title: How to add several GameComponents of the same type?
in order to load 3D-meshes to my project i created a BasicModel class. I made it a DrawableGameComponent so I can override methods like Draw & LoadContent. Plus I have access to the GraphicsDevice etc.

Now I realized that if I try to add several instances of the same GameComponent I get an exception that says that it is not allowed to do this.

1. Was it even a good thing to do, making the Class a GameComponent?
2. Is there a way to somehow differ single Components, so that I can add several copies of it to the game?

Thanks in advance.

# Answer
> 4 votes
> Was it even a good thing to do, making the Class a GameComponent?

No. You should only consider using `GameComponent`s for higher level concepts that sit directly on top of your `Game` class and will only require one instance to exist at any time.

Good examples are classes with *Manager* in their names such as a `ScreenManager`, `InputManager` or `AudioManager`, or classes that are built to be plug and play such as a `FramerateCounter` (see link) that you can easily reuse in any other project just by dropping it in.

So if for instance you created a scene graph class to store and manage the rendering and updating of your game world and all of its objects, you *might* consider making it a `DrawableGameComponent`. On the other hand, using it for each individual game object is not recommended at all.

Personally, I don't even use game components at all. I prefer having precise control over the updating and drawing of my classes, and if I need a reference to `Game` I can pass it on the constructor just as well without making the class a `GameComponent`. Don't let that discourage you from using them though, it's just a matter of personal preference, but just make sure you use them for the *right task*.

---
Tags: xna, game-component
---


# Question
Title: How to Calculate the Contact Point between Ray and Plane
Is there any quick way to find the intersection point between Plane and Ray?

# Answer
> 5 votes
Try the following method which relies on XNA's built in Math API to intersect a `Ray` and a `Plane` and get back the point of intersection:

```
Vector3? GetRayPlaneIntersectionPoint(Ray ray, Plane plane)
{
    float? distance = ray.Intersects(plane);
    return distance.HasValue ? ray.Position + ray.Direction * distance.Value : null;
}

```

The method returns `null` if there's no intersection, or the point of intersection otherwise.

---
Tags: xna, vector, intersection
---


title: C++ Valid for indie 2d games?

text:
# Question
Title: C++ Valid for indie 2d games?
I am not currently developing any games, but am taking a C++ course. Will I actually be able to make any games with the knowledge I have from this course? I really just want to make a game with turrents and units with veterancy, nothing too advanced. But when I search c++ games online, it is nothing compared to the wealth of tutorials etc. provided for actionscript and other languages. thanks.

# Answer
Sure you can make simple games using C++. That's the main language used by game developers; for just one place to start (there are tons, possibly on this site) look at SDL.
> 1 votes

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


# Question
Title: Can I use copyrighted sprites for a demo?
I just had a quick question and wanted everyone's opinions.

I'm making a 2D demo game for a resume which I want to post online. I'm applying as a programmer position so I don't really have my own art. I am planning on using sprite sheets and tile sets from other games in order to create just one or two levels on my demo. I will give credit at the bottom of the screen and state that these sprites are not my own.

Is this a good idea or could this be potentially "dangerous" in the illegal sense?

# Answer
> 16 votes
*I am not a lawyer, the following is not legal advice. If you would like legal advice you should consult a real lawyer. My anecdotes regarding the law are biased entirely towards that of the United States.*

No, you should not use copyrighted sprites (or any other asset) in your demo. It is a bad idea.

* Copyright gives the author of a work (in this case, sprites) the exclusive rights to the use/reproduction/retransmission of the work. To legally use the work, you must have the permission of the copyright holder. Crediting them unsolicitedly or disclaiming that the work is "used without permission" or that copyright infringement is untended is a moot point, because you are infringing regardless. Just because you (or anyone else you may find and point to as an example) hasn't been *caught* doesn't mean it isn't *illegal*.
* Realistically, the odds are against you being sued. The odds are against your infringement even being noticed. You're much more likely just to get a cease-and-desist request than an outright lawsuit. That doesn't make it morally or legally correct, though, and since this is a demo for a career opportunity you should not be building it on such a risky platform.
* Furthermore, this is a demo for a career in an industry that, like it or not, relies in some ways on copyright and IP law. Many people who operate in that industry (myself, for example) have very healthy respect for those laws even if they don't necessarily agree they are perfect. What impression do you think you'd be sending to a potential employer by using somebody else's hard work without their permission? You can't know *a priori* if the people who will review your demo are the kind who will care or not. The kind who will care -- like myself -- will likely look upon your demo far less favorably.
* Finally, it just looks kind of lazy.

You don't need good art to make a good demo, necessarily. Programmers can look beyond the programmer art of other engineers, but far fewer of them can or are willing to look beyond IP violations.

A friend of mine is an IP and entertainment industry lawyer in Seattle; she's written a number of articles on intellectual property issues you mind find interesting.

# Answer
> 10 votes
**The legal perspective:**

No, you cannot legally redistribute someone else's copyrighted work.

This is international law. It is not debatable. It is not made okay by giving credit. It does not become okay by giving it away for free. By copying someone else's copyrighted work, you are violating their copyright -- literally, their exclusive right to make copies. (Yes, there are some circumstances in which you can defend the practice via the doctrine of Fair Use, but this **does not** cover your situation.)

You *cannot* legally redistribute someone else's copyrighted work.

Period.

**An employer's perspective:**

Speaking as someone who is occasionally involved in hiring programmers in the games industry, I would **never** consider hiring someone who submitted a demo containing illegally copied materials. Hell, if the graphics weren't yours, I'd start wondering whether the code was really yours, and whether you didn't just find some code somewhere and re-purpose it.

Hiring a programmer who behaves in this manner would be a massive risk for the company. Imagine the scandal for the company if you did such a thing while working for us, and we didn't notice but you got caught by the media. No, I will not take the chance of hiring someone who has a known history of acting in this way. The risks are too high for me, as a potential employer.

# Answer
> 7 votes
Potentially dangerous in the illegal sense. Not *likely* dangerous. But potentially so, and unnecessarily so, considering how many free sprites are out there. Seriously, dig around on Google, you'll find tons.

# Answer
> 1 votes
I would check the copyright on images, there are companies/artists that doens't like to "share" there sprites, or are constricted to one site or certain goals.

On the other hand there are artists that allows you to use their sprites in any way you want aslong you credit them.

I would advice you to read the policy of the user/company before using their "images". The chance is small that they really going to sue you, but it can. (Think about megaupload)

# Answer
> 1 votes
\[Disclaimer: I am not a lawyer and this is not legal advice.\]

*Generally speaking...*

**No**. You should not — even if you give credit.

*Unless...*

* You **write and ask for permission** and are **given permission in writing**, or
* The copyrighted works are provided under a **license granting you permission** to use them in your own works.

The latter is an important distinction: Just because something is copyrighted doesn't automatically mean that you can't use it. Many creative works are provided under a permissive license *and* are copyrighted. Most likely, the sprites you're referring to aren't released under a license, else you wouldn't be asking. So in your case, I'd definitely write and ask.

*Finally...*

If your demo is just a mock-up that you're going to be showing to people privately — and not publishing on the web — then you don't need permission since you're not publishing the demo. That said, you should still give credit and let viewers know that the sprites are placeholders created by someone else.

# Answer
> -1 votes
Other people had answered about some threats related to using 3rd-party stuff. It´s bad from a legal point of view and also is inadequate about how you are presenting your work. Although that is true that there are lots of images with sharing licenses that you can find at the web if you look, if you want to offer an unique experience to your public, you always can draw your own sprite images, then scan or photo it, and with very basic editing commands at Gimp or Photoshop, you can mount them together. I believe that doing this or asking someone to do something similar, can add some value to the impression about how much you care about the demo you are presenting.

# Answer
> -2 votes
Lost Garden have many good sprites, very handy to prototypes and demos.

http://lunar.lostgarden.com/labels/free%20game%20graphics.html

---
Tags: 2d, sprites, legal, copyright
---


# Question
Title: text wrapping on a texture applied to a 3D model
How would I create and implement a texture of text that wraps around a 3D model? The texture will just be white and you should be able to add text to it, but I need to create this so that when the texture is wrapped around a model of a person, the person is then composed of lines of text and the lines should not be distorted.

In my head the way I would do it is to put the flattened texture in a file, and draw text on to it. Is this the best way? are there any issues that I'm unaware of that I might come across?

# Answer
Here is a link This is part of a DX10 tutorial series, but this one covers rendering to a texture. I think you can abstract it and render text to it very easily. (Never tried to render text in DX before)
> 2 votes

---
Tags: graphics, textures, graphics-programming
---


# Question
Title: Cocos2d animation problem, [__NSCFString rect]: unrecognized selector sent to instance
I am testing (and learning) animation in Cocos2d using a series of .png's called "splash-x.png". I am getting error and at the first sight i thought it was easy to solve but it turned out that i cannot figure out where the problem is. I have tried breakpoints etc. but can still not fix it.

Would any nice person help me to solve this it would be highly appreciated.

Using the following code:

```
-(id) init {
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    // Add background
    CGSize winSize = [CCDirector sharedDirector].winSize;
    CCSprite *bg = [CCSprite spriteWithFile:@"background.png"];
    bg.position = ccp(winSize.width/2, winSize.height/2);
    [self addChild:bg z:-2];

    // Add foreground
    CCSprite *slang = [CCSprite spriteWithFile:@"slangen.png"];
    slang.anchorPoint = ccp(0.5, 1);
    slang.position = ccp(250, 300);
    [self addChild:slang z:1];

    CCSprite *slangslutet = [CCSprite spriteWithFile:@"slanslut.png"];
    slangslutet.anchorPoint = ccp(0, 1);
    slangslutet.position = ccp(390,120);
    [self addChild:slangslutet z:-1];
    CCRotateBy* rotateBy = [CCRotateBy actionWithDuration:1 angle:-180];
    [slangslutet runAction:rotateBy];

    //splash animation
    NSMutableArray *splashAnimFrames = [NSMutableArray array];
    for (int i = 1; i <= 6 ; ++i) {
        NSLog(@">>>>  %i",i);
        [splashAnimFrames addObject:[NSString stringWithFormat:@"splash-%d.png", i]];
        NSLog(@"splash-%d.png", i);
    }

    NSLog(@"%@",splashAnimFrames);

    CCAnimation *splashAnim = [CCAnimation animationWithFrames:splashAnimFrames delay:0.1f];

    self.splashing = [CCSprite spriteWithFile:@"splash-1.png"];
    _splashing.position = ccp(310,330);
    self.walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:splashAnim restoreOriginalFrame:NO]];
    [_splashing runAction:_walkAction];
    [self addChild:_splashing];

 }
return self;
}

```

I get the following error messages:

```
2012-02-02 00:10:38.350 slangtest[8224:10a03] >>>>  1
2012-02-02 00:10:38.350 slangtest[8224:10a03] splash-1.png
2012-02-02 00:10:38.351 slangtest[8224:10a03] >>>>  2
2012-02-02 00:10:38.351 slangtest[8224:10a03] splash-2.png
2012-02-02 00:10:38.351 slangtest[8224:10a03] >>>>  3
2012-02-02 00:10:38.352 slangtest[8224:10a03] splash-3.png
2012-02-02 00:10:38.352 slangtest[8224:10a03] >>>>  4
2012-02-02 00:10:38.353 slangtest[8224:10a03] splash-4.png
2012-02-02 00:10:38.353 slangtest[8224:10a03] >>>>  5
2012-02-02 00:10:38.354 slangtest[8224:10a03] splash-5.png
2012-02-02 00:10:38.354 slangtest[8224:10a03] >>>>  6
2012-02-02 00:10:38.354 slangtest[8224:10a03] splash-6.png
2012-02-02 00:10:38.355 slangtest[8224:10a03] (
"splash-1.png",
"splash-2.png",
"splash-3.png",
"splash-4.png",
"splash-5.png",
"splash-6.png"
)
2012-02-02 00:10:38.356 slangtest[8224:10a03] cocos2d: Frame interval: 1
2012-02-02 00:10:38.507 slangtest[8224:10a03] -[__NSCFString rect]: unrecognized selector sent to instance 0x744f330
2012-02-02 00:10:38.508 slangtest[8224:10a03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString rect]: unrecognized selector sent to instance 0x744f330'
*** First throw call stack:
(0x17e4052 0x1975d0a 0x17e5ced 0x174af00 0x17e51e2 0x6acb3 0x18699 0x104ec 0x2ac6 0x1e08d 0x64906 0x8da1f 0x9000a 0x2a92db 0x2a91af 0x17b8966 0x17b8407 0x171b7c0 0x171adb4 0x171accb 0x2797879 0x279793e 0x82aa9b 0xc086f 0x2145)
terminate called throwing an exceptionsharedlibrary apply-load-rules all

```

**SOLUTION**

Thanks to Robin i figured out the mistake, a BIG thank you. Now i know how this thing works, i think :-)

I also converted the .png's into TexturePacker format. Here is the solution:

```
-(id) init {
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    // Add background
    CGSize winSize = [CCDirector sharedDirector].winSize;
    CCSprite *bg = [CCSprite spriteWithFile:@"background.png"];
    bg.position = ccp(winSize.width/2, winSize.height/2);
    [self addChild:bg z:-2];

    // Add foreground
    CCSprite *slang = [CCSprite spriteWithFile:@"slangen.png"];
    slang.anchorPoint = ccp(0.5, 1);
    slang.position = ccp(250, 300);
    [self addChild:slang z:1];

    CCSprite *slangslutet = [CCSprite spriteWithFile:@"slanslut.png"];
    slangslutet.anchorPoint = ccp(0, 1);
    slangslutet.position = ccp(390,120);
    [self addChild:slangslutet z:-1];

    CCRotateBy* rotateBy = [CCRotateBy actionWithDuration:1 angle:-180];
    [slangslutet runAction:rotateBy];

    //Add splash animation

    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"splash.plist" textureFile:@"splash.pvr.ccz"];
    CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"splash.pvr.ccz"];
    [self addChild:spriteSheet];
    NSMutableArray *walkAnimFrames = [NSMutableArray array];
    for (int i = 1; i <= 6 ; ++i) {
        [walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"splash-%d.png", i]]];
    }

    CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];
    self.splashing = [CCSprite spriteWithSpriteFrameName:@"splash-1.png"];
    _splashing.anchorPoint = ccp(0, 0);
    _splashing.position = ccp(310,330); //winSize.width/2, winSize.height/2);
    self.walkAction = [CCRepeatForever actionWithAction:
                       [CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
    [_splashing runAction:_walkAction];
    [spriteSheet addChild:_splashing];

}
return self;
}

```

# Answer
The problem is in this line of code,

```
CCAnimation *splashAnim = [CCAnimation animationWithFrames:splashAnimFrames delay:0.1f];

```

The variable `splashAnimFrames` is a mutable array containing string values

```
(
"splash-1.png",
"splash-2.png",
"splash-3.png",
"splash-4.png",
"splash-5.png",
"splash-6.png"
)

```

where as it should contain `CCSpriteFrame` objects instead. Check the documentation of `CCAnimation` for more information.
> 3 votes

---
Tags: animation, cocos2d-iphone, ios
---


title: Implementing Object Composition

text:
# Question
Title: Implementing Object Composition
I'm trying to structure my game object classes similar to how it is done in this article. One way to implement this strategy is discussed in this StackOverflow question.

Following the strategy proposed in the linked question above, how would I control how objects are handled based on their implementations?

For example: suppose I have a base class **Item** and two subclasses **ItemPhys** and **ItemStatic**. These two subclasses both extend **Item**. **ItemPhys** implements the interface **Moveable**, but **ItemStatic** does not.

If all of the **Item**'s in my game world are stored in a single **ArrayList** of **Item** objects, how do I make it so `Item::update()` will only try to call `Item::updateMovable()` if the **Item** in question implements **Moveable**?

# Answer
Beware, so that you don't create any tight coupling you are trying to avoid by using this kind of object hierarchy.

I'd suggest you use a uniform way of updating all the components. Let all your entities (e.g. ItemMovable and ItemStatic) implement an `Item::Update()` method. Then call Update on every entity in your system. Do what you have to do for Movable ones and leave the implementation of the `ItemStatic::Update()` empty.

If you're worried about performance (i.e. it turns out to be slow specifically because you're calling too many empty methods), you could keep two lists of entities; one that contains all the entities with meaningful `Update()` method implementations, and one for the rest.
> 3 votes

---
Tags: game-design, java, architecture
---


# Question
Title: How do you extract a Vector3 positions only from a world matrix in an array of positions (from Kinect)
've just started building a physical camera class for the depth data you get from a Kinect. I have a Vector3 array of \[imageWidth, imageHeight\] describing the LOCAL positions I get in from the kinect (once I project them back at the FOV of the camera lens etc). I then translate, scale and rotate the whole virtual kinect camera in space.

What I'm looking to do is to extract back again the positions of the kinect camera input but in WORLD space, not LOCAL space (i.e. it's gone through the translation, scale and rotation and gives me a Vector3 for each value of the kinect in WORLD space).

Any ideas?

# Answer
I have never worked with Kinect so I'm not aware if there are any specific details I'm missing, but have you tried creating a regular world matrix and transforming the local position with it? Something like this for example:

```
Matrix worldMatrix = Matrix.CreateScale(scale) *
                     Matrix.CreateFromQuaternion(rotation) *
                     Matrix.CreateTranslation(translation);

Vector3 worldPosition = Vector3.Transform(localPosition, worldMatrix);

```

*Notes*: For the rotation matrix you can also use `CreateFromYawPitchRoll` or `CreateFromAxisAngle` depending on your needs. Also, this assumes that scaling and rotation happens around the *origin* of the current space.
> 1 votes

---
Tags: xna, matrix, vector, coordinates
---


# Question
Title: What is a fair price to pay for music licensing for a commercial game?
What is a fair price range for already existing (not custom-made) music if it's intended for a commercial game?

The music I have in mind is relatively unknown (independent music) and I'm already in contact with the label that controls the rights to it, I just need a relative price range to take with me into the negotiation.

# Answer
> 15 votes
Jonathan Blow licensed all of the music used on Braid from stock music library Magnatune.com (here's a post on his blog where he talks about it). So I was thinking that perhaps you could get an estimate of a reasonable price from their website. Here's their licensing information page and here's a sample page they provide that lets you estimate the price for licensing one song for a video game.

As an example, here's some results from choosing one random song from that list with the bare minimum choices available (except for the music length):

```
Artist: Ehren Starks
Album: Lines Build Walls
Song name: 01-Lines Build Walls-Ehren Starks
Music length: entire song
Theme song: not theme song
Advertising: no advertising
Number of platforms: 1
Units: 50,000
Price: $1500

```

The website also states the following on the licensing information page:

> Because we've automated the licensing process, **Magnatune's prices are about 30 percent lower than industry standard**.

Draw your own conclusions from there.

# Answer
> 5 votes
This largely depends on how you intend to use the music in this and future related products, how valuable (often gauged by popularity) the music is, and whether you want to buyout the rights or work out a royalty deal.

Here's a link with some general info: http://www.ascap.com/Home/Music-Career/articles-advice/ascapcorner/corner16.aspx

# Answer
> 5 votes
This question is really interesting to me. I have made a deal with a music producer who later became a close friend of mine. We agreed on 7% of total income from sold games.

We found this fair because that way if we both put a large amount of work into a project but no copies are sold, then I'm not X amount of dollars out of pocket. Just his time and mine.

But then conversely if the game in question made millions (pfft, I wish) then we would both get a very decent lump sum. We also took into account the difference in hours worked on a project. He would work on the project about 1 hours to my 10, roughly - so pure time accountancy the rate seemed fair also.

If you're sourcing your stuff from a commercial website, then you're most likely looking at a single payment for the rights of a specific track. About $600-$1500 is probably reasonable. A lot of licenses also scale up. So something like $300 for a game with 3000 copies distributed but $1000 for a game with 100,000 copies distributed.

**It depends on the size of your market *and* your budget, as well as your source.**

---
Tags: audio, music, licensing, pricing
---


# Question
Title: The mosts common topics that developer technical tests ask
> **Possible Duplicate:**
> What are typical job interview questions related to game development?

I have a technical test on the horizon, and I'm brushing up on my 3D maths and algorithmic stuff - there are websites that have lists and lists of technical questions such as 'How would you check to see if a string was a palindrome?' and also perhaps, 'How would you check to see if there was a palindrome anywhere in this string?'

Also things like calculating complex recursion on paper and Big O notation. What are the other key things to practise for these kinds of test?

# Answer
> 2 votes
Practice sleeping well, being on time, taking a bath, dressing well and not least smalltalking well. It's a job, so getting people to like you is way more important than a few points on the technical test.

For the technical part I obviously can't tell you what will be in a test I don't know anything about, but if I were to make such a test I'd probably make it slightly more practical than your list suggests, with stuff like writing a brute force solver for a combinatorics problem or finding bugs or security issues in a given piece of code.

Also be sure that you are well acquainted with reference passing and reference manipulation. That field can make some quick but tricky questions.

Do you know how long the test will be? Unless it's hours you'll probably not be given any real programming task.

# Answer
> 1 votes
Check out The Guerrilla Guide to Interviewing. It might give you an idea of what "people" want when hiring a good programmer.

---
Tags: game-industry, jobs
---


# Question
Title: Can't seem to get predictive collision detection working correctly
I am trying to set up the collision detection on a basic 2d game, player clicks a button sprite moves one step int he corresponding direction.

Currently all my sprites have the collision rectange member:

```
public Rectangle collisionRect
    {
        get
        {
            return new Rectangle(
                (int)position.X + collisionOffset,
                (int)position.Y + collisionOffset,
                frameSize.X - (collisionOffset * 2),
                frameSize.Y - (collisionOffset * 2));
        }//end get
    }//end collisionRect get

```

this works quite well when I try to check to see if the rectangles for 2 sprites overlap

```
 public Vector2 CheckCollision()
    {
        for (int i = 0; i < levelWalls.Count; ++i)
        {
            Sprite wall = levelWalls[i];
            //check for collisions
            if (wall.collisionRect.Intersects(player.collisionRect))
            {
                //remove collided sprite
                levelWalls.RemoveAt(i);
                --i;
            }
        }
    }

```

however I am running into trouble in the part where I check to see if the player's sprite will run into a wall and stopping it. I know I should be doing something like calculating the players next position and seeing if that position collides with any walls and if it does setting it back to an old position, that seems to be a theory that works in my head, however I am having trouble keeping track of Old Position, Current Position and New Position.

Currently I have my player position updating in it's Update() method:

```
position += direction;

```

I then am trying to keep track of old, current and new positions in direction:

```
public override Vector2 direction
    {
        get
        {
            Vector2 inputDirection = Vector2.Zero;

            keyboardState = Keyboard.GetState();
            if (keyboardState.IsKeyDown(Keys.Left) && prevKeyboardState.IsKeyUp(Keys.Left))
                inputDirection.X -= frameSize.X;
            if (keyboardState.IsKeyDown(Keys.Right) && prevKeyboardState.IsKeyUp(Keys.Right))
                inputDirection.X += frameSize.X;
            if (keyboardState.IsKeyDown(Keys.Up) && prevKeyboardState.IsKeyUp(Keys.Up))
                inputDirection.Y -= frameSize.Y;
            if (keyboardState.IsKeyDown(Keys.Down) && prevKeyboardState.IsKeyUp(Keys.Down))
                inputDirection.Y += frameSize.Y;
            prevKeyboardState = keyboardState;
            oldPOS = position;
            newPOS = position + inputDirection;
            return inputDirection;
        }//end get
    } //end Direction

```

My problem is all three: position, OldPOS and NewPOS are always exactly the same. How can I do this better?

**EDIT:** with some help I have worked it down to an issue now with my "collision detection" function

```
public Vector2 CheckCollision(Vector2 oldPOS, Vector2 newPOS)
    {
        bool collided = false;

        for (int i = 0; i < levelWalls.Count; ++i)
        {
            Sprite wall = levelWalls[i];
            //check for collisions
            if (wall.collisionRect.Intersects(player.collisionRect))
            {
                //remove collided sprite
                levelWalls.RemoveAt(i);
                --i;
                collided = true;
                playerPOS = oldPOS;
                break;
            }
        }
        if (!collided)
            playerPOS = newPOS;
        return playerPOS;
    }

```

it always execute the if(!collided) to set the position to the new position, even if i do collide and it removes a wall it never sets my position to the old position.

If I however make (!collided) return the old position I can tell my theory works as my sprite will not move at all.. . .

**EDIT:** AND SOLVED! I needed to create a new colision rectangle for the spot where the sprite will move to, I was using the collision rectangle for where the sprite is! here are the changes:

```
 public Vector2 CheckCollision(Vector2 oldPOS, Vector2 newPOS)
    {
        Rectangle playerCollisionRect = new Rectangle((int)newPOS.X, (int)newPOS.Y, spriteSize.X, spriteSize.Y);

        bool collided = false;
        for (int i = 0; i < levelWalls.Count; ++i)
        {

            Sprite wall = levelWalls[i];
            //check for collisions
            if (wall.collisionRect.Intersects(playerCollisionRect))
            {
                collided = true;
                playerPOS = oldPOS;
                break;
            }
        }
        if (!collided)
            playerPOS = newPOS;

        return playerPOS;
    }

```

# Answer
> 0 votes
The problem I was facing was not with the position of the player nor the variables to keep track of positions. It however was a problem in my check collision function

```
public Vector2 CheckCollision(Vector2 oldPOS, Vector2 newPOS)
{
    bool collided = false;

    for (int i = 0; i < levelWalls.Count; ++i)
    {
        Sprite wall = levelWalls[i];
        //check for collisions
        if (wall.collisionRect.Intersects(player.collisionRect))
        {
            //remove collided sprite
            levelWalls.RemoveAt(i);
            --i;
            collided = true;
            playerPOS = oldPOS;
            break;
        }
    }
    if (!collided)
        playerPOS = newPOS;
    return playerPOS;
}

```

I was taking a bounding box rectangle for each wall and checking it against the player's sprite bounding box as seen here:

```
    if (wall.collisionRect.Intersects(player.collisionRect))

```

However what I needed to do was create a new bounding box based on what would be the player's new position and test that for collision before allowing the move:

```
public Vector2 CheckCollision(Vector2 oldPOS, Vector2 newPOS)
{
    Rectangle playerCollisionRect = new Rectangle((int)newPOS.X, (int)newPOS.Y, spriteSize.X, spriteSize.Y);

    bool collided = false;
    for (int i = 0; i < levelWalls.Count; ++i)
    {

        Sprite wall = levelWalls[i];
        //check for collisions
        if (wall.collisionRect.Intersects(playerCollisionRect))
        {
            collided = true;
            playerPOS = oldPOS;
            break;
        }
    }
    if (!collided)
        playerPOS = newPOS;

    return playerPOS;
}

```

I hope that this helps some one else in their endeavors to begin with game programming!

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


# Question
Title: How can I determine how much I need to rotate an object to face a point?
I have an object located at (208,608) in my 480x800 screen (portrait orientation). I can touch anywhere on the screen (where `y < 608`) and I will get `touchX` and `touchY`.

What is the angle I need to apply to my object so the it will face the point (touchX, touchY)?

I tried

```
double alfa = (float) Math.atan2(touchY-608,touchX-208) * 180 / PI;
myObject.setRotation(alfa);`

```

but this doesn't seem to work if I touch one half of my screen. I also think this might be because the point is located in different quadrants reletive to my start point?

The angle I am trying to get is the angle determined by the two points and the horizontal axis from the first point. What I am trying to do is something like a bow facing my moving finger on the screen. Can anyone help me get the right angle please?

EDIT: I found the answer:

// Calculates an angle a body has to have to face a certain point in space

```
public static float rotateFromPointToPoint(float pFromPointX,float pFromPointY,float
                pToPointX,float pToPointY) {

        float k1 = (float) (pToPointY - pFromPointY);
        float k2 = (float) (pToPointX - pFromPointX);

        float tan = k1 / k2;

        float angle = (float) Math.atan(tan);
        float rotation = (float) Math.toDegrees(angle);

        if (pToPointX < pFromPointX) {
                rotation = (float) Math.toDegrees(angle) + 180;
        }
        return rotation;
}

```

Maybe someone else will find this usefull.

# Answer
`atan2` is better than the code you post as an answer. What you need to do to the angle you get from `atan2` will depend on what your drawing API considers to be the angle 0, but it's probably to add or subtract `pi/2`. One of the eight combinations of `{-1, 1} * atan2(dy, dx) + {0, pi/2, pi, -pi/2}` will work, so if you can't figure it out from first principles you could try all eight until you find the right one.
> 5 votes

---
Tags: game-mechanics
---


# Question
Title: How can animate a set of rigs without reinventing the wheel?
I have a set of rigs of my own defined 3D doll in Javascript. I would like to animate a set of rigs to simulate walking, jumping, etc. Obviously I could do it by myself, but I'm sure I would be reinventing the wheel.

Are there algorithms, libraries (won't matter the language) or anything that I can download and it will give me the position of the rigs in function of time for many animations like walking, jumping?

# Answer
Generally this is done by loading animation data (built in a modelling/animation program like Maya) along with your model and reading the transformation and rotational data for each bone in a rig from there. This is commonly called skeletal animation.

Instead of loading the data from pre-baked animation files, you can adjust the bones procedurally (this would be referred to as procedural animation). Doing this well for very human-like behaviors such as walking, running, and jumping is an ongoing area of research.

There isn't a set of simple equations that you can apply to your bones to get even vaguely realistic motion out of them. Most procedural animation pipelines end up being an exercise in fiddling with a lot of little variables in order to achieve a desired result. You can probably find engines that support full or semi-procedural animation (the Fabric engine claims to), or procedural animation suites that integrate into modelling packages like Maya. There are also papers on the ACM and IEEE sites dealing with the subject, although they are behind membership paywalls so I can't link them directly.

The state of the art (as it is appropriate for and applicable to real-time simulations, like games) is not very great -- 100% procedural animation often looks a bit mechanical.

Now, this isn't to say that procedural animations are of no use; often they are combined with pre-cooked animations, for example by using inverse kinematics to allow for dynamic foot placement on irregular surfaces during idle animations (IK is essentially a method by which you specify the desired target point of the endpoint of a bone chain, and the appropriate displacement and rotation of the bones down the chain can be computed taking into account constraints and whatnot).
> 2 votes

---
Tags: animation, rigging
---


# Question
Title: How to balance audio levels to be loud enough yet safe
There are a few sound effects in my game that sound a bit piercing over earbuds but OK when played through the iPhone speaker. Also sound levels seem lower on older hardware. Is there some objective way to be sure my sounds are loud enough yet safe?

**Notes**: I made my music with GarageBand for iPad. The output was very hot but not clipped. To preview the sounds on my computer I played them in the iPad simulator and matched the volume coming out of my iPhone. To resolve my volume issues, I reduced the high end in Amadeus Pro using the EQ tool. A couple passes for each of the worst sound clips let me reduce the shrillness without muting the volume too badly. Thanks everyone for your help.

# Answer
> 7 votes
I'm not an expert on this field, but this is what my intuition tells me, both from a technical and from a more subjective point of view.

**Technical**

From a technical point of view, in order to preserve quality, you should start by authoring your audio files as loud as possible *but* making sure **not to exceed** a certain volume threshold which would induce **clipping** on the sound's waveform. Most audio software lets you monitor the levels of your file and detect if there's any clipping taking place.

For instance, in Audacity, you can keep an eye on the Meter Toolbar to make sure your file's within an acceptable volume range. Here's what the toolbar looks like, and read the link above for more information. Basically, the meter should never exceed the scale throughout the duration of the file.

You can use effects like *Normalize* or *Amplify* in Audacity to make all of your audio files have the same peak volume without clipping them (in fact by default it normalizes the maximum amplitude to -3dB instead of 0dB, which is probably a good idea too).

**Subjective**

Then there's a more subjective point of view which is, *some* sound effects are by nature more aggressive to the ears and should probably be toned down a bit. This depends mostly in the very nature of the sound, so I'm not aware of any existing procedure to automate this correction.

Therefore my suggestion would be to **use your ears**. In particular, author your audio files *using headphones, and preferably on your iPhone* and try to adjust the volume levels on your audio files manually so that they are as loud as possible *without* getting to the point that they "pierce" your ears.

Possibly ask a few other people around you for opinion too, as different people might have different sensibilities.

# Answer
> 3 votes
This grew to be too big for a comment on David's answer, which I endorse.

A good rule of thumb for correcting for different response is that you want to tone down high-pitched sounds. The general reason is that the frequency response of the ear is stronger at higher frequencies (which isn't surprising, given that the ear is quite small). Obviously it falls away at really high frequencies, but in the range where all you're hearing is third or fourth order harmonics.

But specifically talking about headphones, there are two extra reasons: firstly, they have a higher frequency response at higher frequencies (again, because they're small); so you want to compensate for that. Secondly, because higher frequencies are attenuated more with distance. This means that moving the speakers closer to your ears will tend to over-emphasise the treble.

I don't know the iPhone API. Can you test whether headphones are in use and adjust the level of your sound effects accordingly (or even run them through a different EQ)?

# Answer
> 3 votes
One possible objective method to determine if sounds are loud enough yet "safe" is to measure playback frequency response curves at a range of loudness levels for each target.

For each device and listening output combination you wish to audit, record a series of 5 second sine wave sweeps from 10Hz to 22kHz at a range of playback volumes from quiet to loud, stepping in 3dB increments from -48 dB to -9dB and 1dB increments from -9dB to 0dB. Analyze the recordings of these sweeps to build a map of the level-specific frequency response for each target combination. Use an audio spectral view to visually reveal where frequency response drops off and over-modulates (distorts).

The resultant data set will inform you of the point at which distortion can occur, defining the upper-limit of your safe zone for loudness. Subtract 3dB for each instance of sound layering that might occur to allow a reasonable headroom which will technically not distort the sound.

This does not guarantee subjective assurance to not ever be "too piercing". Because the rate at which a sound replays has a big effect on its annoyance factor, you could reduce volume further based on the count of playback instances per second of a sound in your game.

The above method would be suitable for informing the production of many sounds. If you are only concerned with one sound, then you may substitute that sound for the sine sweeps. Alternatively the sine sweep recordings may be used with audio convolution dsp process to predict the frequency response of any particular sound on any particular target playback combination.

---
Tags: iphone, sound
---