# Question
Title: How do I define a required component on a Unity game object?
I have a script that expected the game object to have a `Terrain` component.

Is there an attribute I can add (or some other way) which will prevent a designer from adding my script/component/MonoBehavior to a GameObject that does not have the `Terrain` component?

The only alternative I have been able to find is to attach my script to something else, and then have a public Terrain field, which requires the user to attach the terrain object to it. (since the editor won't allow you to associate a different object type.) - I just want the reverse.

Any thoughts?

# Answer
Applying the `RequireComponent` decoration to a script will ensure that the GameObject has the specified component.

If the component is missing:

1. Unity will attempt to add a component of this type for you,
2. If this fails (e.g. mixing RigidBody/RigidBody2D) then the script will refuse to attach.

C# sample:

```
[RequireComponent (typeof (Rigidbody))]
public class PlayerScript : MonoBehaviour {
    // stuff
}

```

UnityScript sample:

```
@script RequireComponent(Rigidbody)

// stuff

```
> 11 votes

# Answer
Unity has built in functionality for this called `RequireComponent`. Used like this in Unityscript:

```
@script RequireComponent(Terrain)

```

This will actually automatically add a `Terrain` component to the object if it doesn't have one already. If the user removes the `Terrain` component, your script will throw a compile error about the missing component.
> 3 votes

# Answer
Two methods come to mind, but none are very elegant.

1) Implement `OnValidate()`. The downside is that's it's called only when modifying component's values, or entering/exiting game mode.

```
void OnValidate() {
    if (GetComponent<Terrain>() == null) {
        Debug.LogError("You can't attach this component without terrain!");
        DestroyImmediate(this);
    }
}

```

2) Make the script run in the editor, and implement `OnAwake()`. But be aware that methods like `Update()` will be called in the editor.

```
[ExecuteInEditMode]
class MyScript: MonoBehaviour {
    void OnAwake() {
        if (GetComponent<Terrain>() == null) {
            Debug.LogError("You can't attach this component without terrain!");
            DestroyImmediate(this);
        }
    }
}

```
> 1 votes

---
Tags: unity, component-based, unityscript
---


# Question
Title: Altering Animation Playback Given Terrain Information
Say my character has a jog animation. Assuming Y is vertical, his feet leave the ground at Y=0 and hit the ground again at Y=0. This works fine in a world like that of Minecraft, where every surface the player could traverse is flat.

Now say the character is jogging through hilly terrain. Without any transformations, the animation would break through the ground at certain points. (As the character's foot is lifted and moved forwards, it would go straight through the hill.)

How do I remove this artifact? Do I ask the artists to create separate animations depending on the grade of the terrain? Is there a standard system to resolve animation-world collisions that I'm unfamiliar with? Or is there another more logical approach I haven't thought of yet?

# Answer
There are a number of techniques used to solve this problem. Generally speaking the technique is called Inverse Kinematics, whereby after the pose is complete, the pose is modified to fit to a specific point - hence being Inverse Kinematics - http://en.wikipedia.org/wiki/Inverse\_kinematics

This can be solved through various means - animation or algorithm. Here are some links to techniques, both of which I have seen used on projects I have worked on:

In Mechwarrior, back in 2003, they used a blender to mix different animations to put the feet all in the right places:

http://www.gamasutra.com/view/feature/131863/animation\_blending\_achieving\_.php

In Zoo Tycoon, they used a PID algorithm to get the feed to line up with the terrain. Again, back in 2004 - search for Zoo Tycoon the the following PDF:

http://twvideo01.ubm-us.net/o1/vault/GD\_Mag\_Archives/Game.Developer.2004.06-07.pdf

The actual path you need to follow will depend on performance limitations, and the aesthetics needed. PID, or blending, or serious IK solving - it's something you need to experiment with and decide.

Here's links to more samples:

http://www.3dkingdoms.com/ik.htm http://www.emagix.net/academic/item/inverse-kinematics-solver-in-c

Good luck!
> 1 votes

---
Tags: physics, animation
---


title: How do I draw a tilemap within unity3d?

text:
# Question
Title: How do I draw a tilemap within unity3d?
I'm pretty new to Unity and after a bit of googling around I have come up with this code to draw my tilemap (the script is attached to my camera).

I am simply trying to use nested for-loops to draw a grid of grass tiles, here is my code:

```
public class DrawMap : MonoBehaviour {

    // Use this for initialization
    void Start () {

        Sprite grass = (Sprite)Instantiate(Resources.Load("Grass"));
        float x, y;

        for (int i = 0; i < 20; i++) {
                        for (int j = 0; j < 20; j++) {
                            x = i * 1.28f;
                            y = j * -1.28f;
                            Instantiate(grass, new Vector3 (x, y, 0f), Quaternion.identity);

                        }
                }
    }

    // Update is called once per frame
    void Update () {

    }
}

```

I keep getting an error where I initialize "grass" saying the it cannot cast the source type from the destination type. I created "grass" to be a prefab from a slice of a spritesheet that i imported.

Any help would be greatly appreciated

# Answer
> 5 votes
Ok seems as no one is replying to you, I will provide you with a basic commented example.

I assume you have a "Resources" folder inside of your "Assets" folder. I also assume you have a "Prefabs" folder inside of your "Resources" folder.

You will need to create an empty GameObject in your scene. Attach a SpriteRenderer component to that object and then drag your desired grass sprite into the Sprite section of the SpriteRenderer. Drag that object into your "Resources/Prefabs" folder. The destination is important because we will be loading it from script later. Delete the initial (not prefab in folder) GameObject in your scene because we already have a copy of it.

Now you have created a tile prefab which can be used for the basic example tile map. Please note that this is for explanation purposes and would need some slight modifications to have multiple tiles instead of just one.

Now you will need to create a new GameObject in your scene and name it "TileMap" or whatever you want…

Create a new C# script and name that "TileMap" or "Map" or whatever you want… Attach that script to the "TileMap" GameObject.

Open up the C# script and insert the below code into it.

**NOTE** the code is commented and I shouldn't have to re-explain it to you. Good luck.

```
//Place a gameobject with a sprite renderer attached and the grass tile in that.
//Create it into a prefab and place it into your "Resources" folder.
public Transform tilePrefab;

//Tilemap width and height
public int mapWidth = 5;
public int mapHeight = 5;

//Size you want your tile in unity units
public float tileSize = 1.28f;

//2D array to hold all tiles, which makes it easier to reference adjacent tiles etc.
public Transform[,] map;

void Start ()
{
    //Load prefab "Grass" from "Resources/Prefabs/" folder.
    tilePrefab = Resources.Load <Transform> ("Prefabs/Grass");

    //If we can't find the prefab then log a warning.
    if (!tilePrefab)
        Debug.LogWarning ("Unable to find TilePrefab in your Resources folder.");

    //Initialize our 2D Transform array with the width and height
    map = new Transform[mapWidth, mapHeight];

    //Iterate over each future tile positions for x and y
    for (int y = 0; y < mapHeight; y++)
    {
        for (int x = 0; x < mapWidth; x++)
        {
            //Instantiate tile prefab at the desired position as a Transform object
            Transform tile = Instantiate (tilePrefab, new Vector3 (x * tileSize, y * tileSize, 0), Quaternion.identity) as Transform;
            //Set the tiles parent to the GameObject this script is attached to
            tile.parent = transform;
            //Set the 2D map array element to the current tile that we just created.
            map[x, y] = tile;
        }
    }
}

//Returns a tile from the map array at x and y
public Transform GetTileAt (int x, int y)
{
    if (x < 0 || y < 0 || x > mapWidth || y > mapHeight)
    {
        Debug.LogWarning ("X or Y coordinate is out of bounds!");
        return null;
    }
    return map[x, y];
}

void Update ()
{

}

```

---
Tags: unity, tilemap
---


title: Collision detection Libgdx

text:
# Question
Title: Collision detection Libgdx
I'm trying to implement Collision detection using Rectangles for my game but can't seem to get it to work.

Bullets are updated when pressing space every frame so they move across the screen. Apparently so I've been told on here, the collisionbox moves with it as well. I'm getting this by using `sprite.getBoundingBox()` which sets a datafield Rectangle to this value for each instance.

I have two Arraylists, one holding instances of Monsters and one holding instances of Bullets. They all have collisionRectangles associated with them.

I'm calling the `checkCollisions()` method from my main render loop every frame as long as there's something in the bullets or monsters arraylist.

```
/*this handles collisions between bullets and enemies*/
public static void checkCollisions(){
    for (int i = 0; i < Main.currentBullets.size(); i++){
        for (int k = 0; k < Main.currentMonsters.size(); k++){
            if (Intersector.overlaps(Main.currentBullets.get(i).collisionBoxBullet,
                  Main.currentMonsters.get(k).collisionBoxMonster)){
                     System.out.println("Boom headshot");
                }
        }
    }

```

Why does it keep writing Boomheadshot to standard out even when its not colliding with an enemy?

# Answer
In the inner `for` loop, shouldn't you be incrementing `k` instead of `i`? You're doing `i++` twice, so at some point, your code is trying to access `Main.currentBullets.get(10)`, which is causing your `Index 10, size 10` to get thrown.
> 0 votes

---
Tags: java, libgdx, game-mechanics
---


# Question
Title: Specular light flickering with high specular power
I'm having some issues with specular lights, to be more specific, the specular color seems to be flickering when I set high power, like 512 (I set the specular color to green, so you can see better):

https://i.stack.imgur.com/SNAmA.gif

And when a power like 32 is used, everything seems ok:

Pixel shader hlsl:

```
pin.NormalW = normalize(pin.NormalW);

float3 toEyeW = normalize(gEyePosW - pin.PosW);

// Start with a sum of zero.
float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f);
float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f);
float4 spec    = float4(0.0f, 0.0f, 0.0f, 0.0f);

// Sum the light contribution from each light source
float4 A, D, S;

ComputeDirectionalLight(gMaterial, gDirLight, pin.NormalW, toEyeW, A, D, S);

ambient += A;
diffuse += D;
spec    += S;

float4 litColor = ambient + diffuse + spec;

litColor.a = gMaterial.Diffuse.a;

return litColor;

```

ComputeDirectionalLight function:

```
void ComputeDirectionalLight(Material mat, DirectionalLight L,
  float3 normal, float3 toEye,
out float4 ambient,
out float4 diffuse,
out float4 spec)
{
      // Initialize outputs.
      ambient = float4(0.0f, 0.0f, 0.0f, 0.0f);
      diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f);
      spec = float4(0.0f, 0.0f, 0.0f, 0.0f);

      // The light vector aims opposite the direction the light rays travel.
      float3 lightVec = -L.Direction;

      // Add ambient term.
      ambient = mat.Ambient * L.Ambient;

      // Add diffuse and specular term, provided the surface is in
      // the line of site of the light.

      float diffuseFactor = dot(lightVec, normal);

      // Flatten to avoid dynamic branching.
      [flatten]
      if (diffuseFactor > 0.0f)
      {
          float3 v = reflect(-lightVec, normal);
          float specFactor = pow(max(dot(v, toEye), 0.0f), mat.Specular.w);

          diffuse = diffuseFactor * mat.Diffuse * L.Diffuse;
          spec = specFactor * mat.Specular * L.Specular;
      }
  }

```

I'm using DirectX 11.

# Answer
> 0 votes
The problem is that L.Direction vector is not normalized, so the dot product "max(dot(v, toEye)" is calculating |v|\*cos Θ instead of cos Θ, which is not what we want. So normalizing it on CPU side solves the problem. Thank you @snake5 for helping me on chat with it.

---
Tags: 3d, graphics, directx11, lighting
---


title: How to move 2D camera in OpenGL

text:
# Question
Title: How to move 2D camera in OpenGL
I am new in OpenGL, I am making a game in 2D and I want the camera to follow the character.

I started with `gluLookAt()` but I read that I could just move the matrix with `glTranslatef()` and It should do the trick.

The problem is the camera only move the first time It is created but if I increment the X position and Y position It doesn't work. What I m doing wrong? I have incorrect concepts?

I tried it changing to GL\_PROJECTION,GL\_MODELVIEW, AND GL\_TEXTURE,

If I do it on GL\_PROJECTION all the items are gone ( thanks to the question answer link I understand that I cant take that way)

If I do it on GL\_TEXTURE all the textures start to scroll ( but that is not what i want

If I do it on GL\_MODELVIEW just nothing happen all the item are in the same site but if I quit the gl.glMatrixMode(GL10.GL\_MODELVIEW) line above translatef It move the camera the first iteration and then stop to do it since the last object is on GL10.GL\_MODELVIEW

Is at the start at different matrix state?

My render code:

```
public void onDrawFrame(GL10 gl)
{
    loopStart = System.currentTimeMillis();
    try
    {
        if (loopRunTime < SEngine.GAME_THREAD_FPS_SLEEP)
        {
            Thread.sleep(SEngine.GAME_THREAD_FPS_SLEEP - loopRunTime);
        }
    } catch (InterruptedException e)
    {
    }
    deltaTime = (float) ((System.currentTimeMillis() - aRestar)/1000f);

    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glClearColor((78.0f / 255.0f), (192.0f / 255.0f), (203.0f / 255.0f), 0.0f);

    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glTranslatef(x, y, 0f);

    perro.draw(gl);
    palmera.draw(gl);

    comprobacionesColision();
    actualizar(deltaTime);

    x +=0.05f;
    y +=0.05f;

    loopEnd = System.currentTimeMillis();
    loopRunTime = ((loopEnd - loopStart));

}

```

# Answer
> 1 votes
Ok after a lot of tries I made it,Stil I dont know if this is the best way to achieve this, if someone can explain why this is a solution it will be good!

I just change the matrix mode to GL\_PROJECTION and translate it

```
gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glOrthof(0f, 8f, 0f, 4f, -1f, 1f);
    gl.glTranslatef(x, y, 0f);

```

instead of

```
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glTranslatef(x, y, 0f);

```

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


# Question
Title: Implementing one-way platforms in Chipmunk
I am making game in cocos2d-x, but it's the first time I am using a physics engine i.e. Chipmunk. (It's built-in to cocos2d-x.)

I want to make a one-way platform: When my character jumps into a platform from below, they *should not collide*, but when falling on to one from above, they *should collide*. Then the player could jump up onto platforms from below, like this:

# Answer
I think I can help you someway. In Cocos2dx we could handle collision event with `EventListenerPhysicsContact`.

check out this code:

```
auto character = Sprite::create("chacracter.png");
auto body = PhysicsBody::createCircle(sprite->getContentSize().width / 2);
body->setContactTestBitmask(-1);
body->getFirstShape()->setMass(200);
character->setPhysicsBody(body);
character->setPosition(Vec2(300,250));
this->addChild(character);

auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin= [=](PhysicsContact &contact) -> bool
{
    // We we handle what happen when character collide with something else
    // if we return true, we say: collision happen please. => Top-Down Char Jump
    // otherwise, we say the engine to ignore this collision => Bottom-Up Char Jump
    auto character = contact.getShapeA()->getBody()->getNode();
    if( character.isJumpingUp() )
            return false;
    else
            return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, character);

```

In `contactListener->onContactBegin` we handle what should Chipmunk do when chcarcter collide with collision line. sometimes ignore, sometimes not.

Hope Help You
> 2 votes

# Answer
I'm assuming that the physics engine for cocos2d-x already has this ability and you will just need to dig a little bit more.

Otherwise, I'm also thinking of trying to implement something similar myself for a mockup game I'm trying to create. Right now (not sure whether it's a good idea or not) I'm thinking of adding a new property that determines what kind of collision can apply to a certain object. And depending on the velocity/accel (whatever your movement indicator is defined as) will be the check for this collision.

You can also check this out: http://www.wildbunny.co.uk/blog/2011/12/14/how-to-make-a-2d-platform-game-part-2-collision-detection/

It has some in-depth explanation of how to implement a kind of collision detection and it also includes your question.

Update: From my understanding... the key conditions for a one-way platform are:

* if the velocity of the object is positive, ignore the collision.
* if the base of the object's position is less than the position of the top of the platform, ignore the collision.

You will need to determine what kind of conditions are required for a one-way platform.

On another note, I went and took a quick look into Chipmunk and it looks like one-way platform is very trivial.

Here's a code snippet from the Demo Chipmunk provides:

```
// Add our one way segment
shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-100), cpv(160,-100), 10.0f));
cpShapeSetElasticity(shape, 1.0f);
cpShapeSetFriction(shape, 1.0f);
cpShapeSetCollisionType(shape, 1);
cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

// We'll use the data pointer for the OneWayPlatform struct
platformInstance.n = cpv(0, 1); // let objects pass upwards
cpShapeSetUserData(shape, &platformInstance);

//at the very end
//preSolve -> looks like checking the direction of the object with a normal vector
//and fails the collision if the direction of the normal is negative
  cpSpaceAddCollisionHandler(space, 1, 2, NULL, preSolve, NULL, NULL, NULL);

```

The file is called OneWay.c https://github.com/slembcke/Chipmunk2D/blob/master/Demo/OneWay.c
> 0 votes

---
Tags: collision-detection, platformer, cocos2d-x, chipmunk
---


title: iOS gaming with copyrighted characters?

text:
# Question
Title: iOS gaming with copyrighted characters?
Can I use animate characters in an iOS game if I do a citation in the credits. Ex Steven univers in a fighting game and I list Rebecca Sugar in the Credits or by the character bio.

# Answer
> 2 votes
No.

While the details of copyright law varies by jurisdiction (US versus Europe for example), the general thrust is basically the same: copyright gives the author of the work the control over who can use the work and how. It is only okay to use somebody's copywritten work if they have explicitly permitted you to do so.

"Giving the author credit" or "not making a profit" do not exempt you from copyright law.

The one real exception is "fair use" doctrine, which permits certain usages under certain very specific and limited scenarios. You're game almost certainly does not fit the criteria.

You should always consult a lawyer for legal matters such as these. If you feel like you "cannot afford" a lawyer then you absolutely should not be trying to skirt copyright law because getting sued or suffering a cease-and-desist is far more expensive or impactful.

Use your own imagination. Make your own games.

---
Tags: game-design, ios, copyright
---


# Question
Title: c++ RPG - Handling buffs / equipment stats
I'm trying to develop a character calculator for a RPG, and it could evolve into a turn based combat / text based RPG. One of my concerns is how to handle the equipment stats / buff system.

Currently each of my buffs / equipment object and my character object itself has a member `bonusstats`, which is a struct containing a (potentially) very large amount of possible modifiers (attributes, misc\_skills, protections, secondary\_stats, etc and their multiplier versions).

```
struct BonusStats {
    int attribute[8], misc_skill[30], protection[9], HP, MP, ... ;
    //define constructor, operator+=, reset function
}

```

And everytime an actualize call is requested every stat is recomputed:

```
Character::Actualize() {
    this->bonusstats.reset();
    for /*iterate through vector of buffs and equipped items*/ {
        this->bonusstats += item->getBonusStats();
    }
}

```

While this is a rather simple approach I am concerned about two things mainly:

1.- Is it performance-wise acceptable? I get the feeling that having to sum two structs containing 100 elements just to add a buff is not a very good practice. Would there be any practical advantage in using a function like `Character::ApplyStats( std::function<void(BonusStats*)> itemstats)` instead?

2.- How could I implement more complex buffs than stat modifiers? For example, reflecting x% damage when blocking a melee attack. The thing that comes to my mind is to create complex stats like `percent_damage_reflected_on_melee_block` and check its value everytime conditions are met. Is it a good approach?

# Answer
> 0 votes
I would switch from having a function that adds stats to a function that takes in the entity with the equipment or buffs and make the item responsible for modifying the entity. Something like...

```
Character::Actualize() {
    this->bonusstats.reset();
    for /*iterate through vector of buffs and equipped items*/ {
        item->applyEffect(this); // Maybe a reference? Dunno, don't use c++ anymore.
    }
}

```

I have a VERY similar system in one of my games and not only is it performant enough to have hundreds of buffs, most of those buffs are sending network calls in my game and it still works fantastically. Iterating through a loop and doing some basic math is nothing compared to the performance of draw calls.

As for the different types of events, the best way is some kind of event system where the buffs or items can register for the events. There should be a ton of libraries for those, but it's also a simple system to write yourself.

---
Tags: c++, rpg, statistics, effect-modifier
---


# Question
Title: How can I position a sprite in the same spot across different screen sizes?
Taking into account the multitude of screen sizes and resolutions, is there a way I can position a sprite so it's at roughly the same spot on every iOS device?

Doesn't matter if you are using SpriteKit or Cocos2D or just using UIKit. The principle for positioning a sprite is roughly the same.

# Answer
You have only two main options, both of which have serious pros and cons:

* Use normalized positioning, so that the X and Y coordinates are expressed effectively as a percentage of the available width and height.
* Use absolute positioning, so the X and Y coordinates are exactly the pixel or point coordinates of the sprite on the screen.

Relative positioning will make sprites appear more-or-less in the same place, as you are asking for, so it's probably what you want to use for the sprites in question.

However, it will not preserve distances between sprites. Two objects at 10% and 90% of the screen width will be further apart on a wider screen. This may be detrimental for gameplay.

You can scale the sprites up accordingly, which can make the distances the same, but that introduces either visual artifacts due to scaling or the requirement for multiple resolutions of sprite assets. A potential happy medium is to author the sprites at the highest resolution, as you can downscale cheaply with fewer artifacts than you can upscale cheaply. Although you could also employ a cleanup algorithm after upscaling if you have the computational bandwidth.

Absolute positioning avoids the distance issues as well, but also means you don't utilize the extra screen real estate. It's left blank (or filled in with 'letterbox' UI chrome), or it allows a player to see more of the gameplay, possibly imparting undesirable gameplay advantage to those with larger screens. Or it implies you need to author layouts for every possible screen resolution, which is tedious.

Using one method or the other universally is probably not a good idea. Instead, mix and match them according to the particular requirements of whatever visual component of your game you're currently working on.

For example, you might position all the game world objects with an absolute model, but use relative metrics for positioning UI elements on the screen.

You can also hybridize the methods, which works particularly well for UI, where you specify absolute distances relative to other objects in the scene, usually expressed with min/max constraints, and re-flow the layout of the objects at runtime in a way that satisfies those constraints.
> 5 votes

---
Tags: game-design, mathematics, sprites, ios, gui
---


# Question
Title: Unity GUITexture or GUIText not showing up
Currently I've got a little 2.5D platformer with the camera tracking the player. Now when I go to insert a GUITexture or GUIText game object into the scene, it comes up absolutely fine in the Editor view, but when I go to play it there's absolutely nothing to be seen!

At first I thought it may have been a script I was using on the GUI, but I've tried it out with a completely bland GUITexture object that has no interaction with the rest of the game and I still get the same effect. I'm wondering if my camera is messing it up somehow, but I assumed that all GUI objects are drawn to screen space and just stay with the camera.

I've been really stuck for the past few hours so if any one could offer some insight, I'd be very, very grateful!

~Ray

# Answer
> 5 votes
I can safely say that I am an idiot :)

Somehow, my camera got rid of the GUILayer component. Creating a new camera from scratch with all the prefabricated components fixed it.

I'll leave this here for posterity's sake, since this would be a pretty obscure thing to go wrong and there isn't any documentation I found on it.

But if a moderator feels differently, then they can close it :)

# Answer
> 1 votes
Make sure that you have selected a Game view like below:

---
Tags: unity, gui
---


# Question
Title: How can I run two CCActions in parallel and another one afterwards with Cocos2D?
With Cocos2D I can run two actions in parallel by simply using `runAction` and I can use a `CCSequence` two run several actions after each other. However what I could not find is:

* Run two actions simultaneously
* When both actions are done, trigger a third `CCAction`

It must be really easy but I seem to use the wrong search keywords on Google. :-)

The only possible solution I have found so far is to use a delayed action as the first element of a CCSequence and then start the third action. But it "feels" wrong.

# Answer
> 3 votes
Use this code (cocos2dx v3.x):

```
node->runAction( Sequence::create( Spawn::create(A, B, nullptr),
                                    C,
                                    nullptr));

```

This is what happen:

1. A and B start simultaneously
2. After the longer one finished, C start.

Important: Remember that you should use finite action when using `Sequence`. for example you should not use `RepeatForever` for actions when use them in `Sequence`.

---

cocos2d v2.x

```
node->runAction( CCSequence::create( CCSpawn::create(A, B, NULL),
                                    C,
                                    NULL));

```

---
Tags: cocos2d
---


title: Bloom control - enlarging glare area

text:
# Question
Title: Bloom control - enlarging glare area
I am trying to improve my bloom system. So far I have bloom that looks like this:

What I need is to enlarge the low-bloom areas to make it look like this:

Simply increasing the bloom multiplier results in a linear brightness shift and the lantern's top gets completely lost in a bright epicenter. What I need is a non-linear system that alows to only enlarge bloom on the edges. I tried different approaches and was able to come up with the following formula:

```
float luma = min(dot(AccumulatedBloom.rgb, LUM_CONVERT), 1);
float bloomMultiplier = lerp(1, bloomAuraMult, pow(1 - luma, bloomAuraPower));

```

But this formula has a disadvantage, it makes the bloom look like this:

Could anyone help me find the right formula?

# Answer
Bloom effect filters are usually circularly symmetric or *isotropic*. You can't achieve your goal by solely modifying the radial shape of the filter, since it won't break the symmetry.

However, to implement the desired effect, you can use e. g. the stencil buffer to mask out the region you want to remain dark. Alternatively you can create a texture of the light aura which captures specifically the shape you need. I'm sure there are countless other ways to do it, these are just some quick examples.
> 2 votes

---
Tags: shaders, bloom
---


# Question
Title: What are "supporting points" in the context of the SAT?
I am currently implementing a separating axis theorem collision response. It can be used by oriented bounding boxes and axis-aligned bounding boxes.

So far I have covered face-something contacts. I struggle witth the edge-edge cases. I know the all the axis, penetration depth and the collision normal. But I don't understand the how I can receive a contact point. I read something about using supporting points but what is a supporting point? There are just a few explanations with even less information.

Do you know a good source which explains something? I already digged into some source code of different physic engines. But every engine calculates it different and the comments often don't even exist.

# Answer
> 1 votes
The supporting point is the point that lies at the penetration depth. If you already have working SAT then you've already used the supporting point as otherwise you'd have no way to find penetration depth for OBBs. The supporting point might be buried or abstracted by the specific implementation of SAT you're using, though (if you derive from basics, you'll be working with it, but the shape-specific simplifications of SAT can avoid needing an explicit point for many shapes after simplifying all the math).

The supporting point is one thing you can find to get contact points. You use this point to help identify the *incident edge* and *reference edge* of the shapes. Then you use polygon clipping to find one, two, or more (for 3D) points that have the most impact on collision resolution.

This is commonly referred to as the *contact manifold*.

See Randy Gauls' articels on physics for some details on finding the contact points. Read the whole series.

---
Tags: 3d, terminology, separating-axis-theorem
---


title: Sprites get terribly scaled

text:
# Question
Title: Sprites get terribly scaled
I've been making a Space Invaders game in XNA for a while. I got the invaders animated and contained within an array. But when I call `spriteBatch.Draw` and debug the invaders sprites get a **huge** scale-up! Here is my code:

```
        public static Texture2D g_BotInvaderTex;
        public static Rectangle g_BotInvaderHitBox;
        public static Vector2 g_BotInvaderPos = new Vector2(0, 24);
        public static Vector2 g_BotInvaderOrigin;
        public static Rectangle[,] g_BotInvadersRect;
        int m_InvaderRows = 5;
        int m_InvaderCollumns = 10;
        public static Color InvadersColor = Color.White;

        // blah blah sprite animation logic

        public void Draw(Texture2D texture, Vector2 position, Rectangle[,] destinationRect, Nullable<Rectangle> sourceRect, Color color, float rotation, Vector2 origin, SpriteEffects effects, float scale, SpriteBatch spriteBatch)
        {
            for (int r = 0; r < m_InvaderRows; r++)
            {
                for (int c = 0; c < m_InvaderCollumns; c++)
                {
                    spriteBatch.Draw(g_BotInvaderTex, g_BotInvadersRect[r, c], g_BotInvaderHitBox, Color.White);
                }
            }
        }

```

After I intialize the invader class in my Game1 and call Draw:

```
botInvader.Draw(botInvaders.g_BotInvaderTex, botInvaders.g_BotInvaderPos, botInvaders.g_BotInvadersRect, botInvaders.g_BotInvaderHitBox, Color.White, 0f, botInvaders.g_BotInvaderOrigin, SpriteEffects.None, 1.0f, spriteBatch);

```

I don't think the sprites should be scaled up, after all I've given `1.0f` to the scale argument???

```
        for (int r = 0; r < m_InvaderRows; r++)
        {
            for (int c = 0; c < m_InvaderCollumns; c++)
            {
                g_BotInvadersRect[r, c].Width = g_BotInvaderTex.Width;
                g_BotInvadersRect[r, c].Height = g_BotInvaderTex.Height;
                g_BotInvadersRect[r, c].X = 70 * c;
                g_BotInvadersRect[r, c].Y = 70 * r;
            }
        }

```

# Answer
In your loop, you are using this overload: http://msdn.microsoft.com/en-us/library/ff433987.aspx, which instead of specifying a scale, specifies destination and source rectangles.

It's hard to tell from the names you chose if you provided the correct rectangles, but you specified `g_BotInvadersRect[r, c]` as the destination (screen bounds) and `g_BotInvaderHitBox` and the source (spritesheet location).

If you place a breakpoint on that draw method and take a look at the value of `g_BotInvadersRect[r, c]`, you should see the actual destination rectangle for that sprite, which according to your problem description is the wrong value. Your issue is most likely that your destination bounds were not calculated correctly.
> 0 votes

---
Tags: xna, c#, spritesheet, scale
---


title: SDL_UpdateTexture is slow

text:
# Question
Title: SDL_UpdateTexture is slow
I am raytracing on the CPU and I need to display my renders to the screen in realtime. I chose SDL 2 as it seems to be made for low level stuff.

I made this basic test which fills the screen from left to right, one column of pixel per frame. It works as expected, but runs very slowly (~10 fps):

```
int resolutionX = 1920, resolutionY = 1080;

if (SDL_Init(SDL_INIT_VIDEO) != 0)
    return EXIT_FAILURE;

SDL_Window *window = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, resolutionX, resolutionY, SDL_WINDOW_SHOWN);
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
PixelBuffer *framebuffer = createPixelBuffer(resolutionX, resolutionY);
SDL_Texture *framebufferTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, framebuffer->width, framebuffer->height);

for (int x = 0; x < resolutionX; x++)
{
    for (int y = 0; y < resolutionY; y++)
        setPixel(framebuffer, x, y, 0x123456FF);

    SDL_UpdateTexture(framebufferTexture, NULL, framebuffer->pixels, framebuffer->pitch);
    SDL_RenderCopy(renderer, framebufferTexture, NULL, NULL);
    SDL_RenderPresent(renderer);
}

SDL_DestroyTexture(framebufferTexture);
destroyPixelBuffer(framebuffer);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

```

I found `SDL_UpdateTexture` to be the slowdown.

~~I heard of `SDL_LockTexture` but I don't think I should be using it for write-only operations.~~
**EDIT :** `SDL_LockTexture` is in fact exactly made for write-only operations.

Am I using this function in a wrong way ? Is there any other way to display my renders in real time ?

# Answer
> 10 votes
Creating a texture with the pixel format `SDL_PIXELFORMAT_RGBA8888` was the error here. This format might be different from the one used on the GPU, and the texture had to be converted each frame.

I found that using `SDL_PIXELFORMAT_ARGB8888` instead completely solved this issue, and uploading the texture is now instant.

Although the documentation says that `SDL_UpdateTexture` is slow and should be optimized by using `SDL_LockTexture`, I haven't noticed ANY performance boost with it.

# Answer
> 7 votes
> I found SDL\_UpdateTexture to be the slowdown.

The SDL documentation for `SDL_UpdateTexture` explicitly says in the Remarks section that it is a slow function and only meant for static texture uploads.

> I heard of SDL\_LockTexture but I don't think I should be using it for write-only operations.

The documentation for `SDL_LockTexture` explicitly says in the Remarks sections that it is intended purely for write operations (which is one of the reasons it's so much faster for this purpose).

---
Tags: sdl2
---


# Question
Title: Compiling a shader with fxc results in invalid ps_5_0 output semantic 'COLOR0'
I'm attempting to compile a shader at the command prompt. What am I doing wrong that would make it generate this error?

```
fxc /Od /Zi /T ps_5_0 /E "ps_main" /Fo "basic.pso" "basic.ps"

```

Here is the pixel shader

```
struct VS_OUTPUT
{
    float4 Color    : COLOR0;
};

float4 ps_main(VS_OUTPUT input) : COLOR0
{
    return input.Color;
}

```

The return is:

```
<path here>\basic.ps(8,33-40): error X4502: invalid ps_5_0 output semantic 'COLOR0'

compilation failed; no code produced

```

# Answer
COLOR0 is DX9. Since you're dealing with DX11 (ps\_5\_0) you need to replace `COLOR0` with `SV_Target`.
> 5 votes

---
Tags: directx, directx11, hlsl
---


# Question
Title: How can I load a level using a sound file? [JAVA]
I'm trying to load a level from a music file (mp3, midi, etc, I'm not picky) for a rhythm-based game. I must be searching in all the wrong places because I can't seem to find any help on this topic.

(I am using Eclipse Luna, AndEngine, Android SDK Tools 20.0.5 and ADT 23.0.4)

My plan was to stream the music file at run-time and create objects when certain pitches, etc are reached, but I have no idea how to do this in Java? Are there any libraries, etc I should be using or is this just not possible?

# Answer
It seems to me that you will need to perform some sort of Frequency analysis on the audio file in question. You could either pre-process the file on level load (using the data to queue up your level actions), or perform the analysis in real-time.

Either way, you'll want to divide your audio waveform into sections, each comprised of N samples, and then perform a Fourier Transform on those N samples. This will give you frequency data for that section of time in your audio, from which you can decide what to do in your game (e.g. drop a bomb on a bass kick).

If you instead perform a transform on the whole song, you will get the frequency data for **the whole song. Which you probably don't want**, as you will no longer know at what points in time the frequencies occur. *However*, you could use this information to theme your level (e.g. lots of bass = some sort of underground level or somesuch).

In order to do that in a reasonable amount of time (pre-processing or real-time), you'll want to implement a Fast Fourier Transform algorithm. The Cooley-Tukey algorithm is apparently pretty commonly used. If you don't want to try to implement such an algorithm yourself, JTransforms is a multi-threaded FFT library for Java, and Kiss FFT, while in C, has a BSD license *(and you may be able to find a java wrapper for it)*.

**Addendum:** You will also probably want to take a look into whether or not applying a Windowing Function affects your output in a significant way. In the above, taking N samples, a Rectangular Window Function is applied automatically.

From Information I have found, it appears that most people don't worry too much about dealing with a Window Function for the FFT.
> 3 votes

# Answer
This is definitely possible. I would look into this book or ebook online and it teaches you how to write effective sound classes so that you can use them in the future, with situations like you are speaking of.

You can iterate through samples in any sound file and throw flags on high/low pitches, amplitudes, frequencies, etc..

Here is the book:

http://www.amazon.com/Introduction-Computing-Programming-Java-Multimedia/dp/0131496980

Once you have the sound class down, you can store the samples into an obj, then use that obj on the fly. Instead of trying to iterate through the sound file as it is playing.
> 0 votes

---
Tags: java, android, andengine, music, eclipse
---


# Question
Title: How to invisible first window on click unity3d
I have a window called "red window" on scene1. When i click on the hello world button it should displays another window called green window and the first window should invisible. How it possible.

```
using UnityEngine;
using System.Collections;![alt text][3]

 public class window : MonoBehaviour {
 private bool render = false;
 public Rect windowRect0 = new Rect(20, 20, 120, 50);
 public Rect windowRect1 = new Rect(20, 100, 120, 50);
 void OnGUI() {
     GUI.color = Color.red;
     windowRect0 = GUI.Window(0, windowRect0, DoMyWindow, "Red Window");
     GUI.color = Color.green;
    windowRect1 = GUI.Window(1, windowRect1, DoMyWindow1, "Green Window");
 }
 void DoMyWindow(int windowID) {
     if (GUI.Button (new Rect (10, 20, 100, 20), "Hello World")) {
         }

       //GUI.DragWindow(new Rect(0, 0, 10000, 10000));
   }
  void DoMyWindow1(int windowID) {
 if (GUI.Button(new Rect(10, 20, 100, 20), "Hello World"))
     print("Got a click in window with color2222222222 " + GUI.color);
 //GUI.DragWindow(new Rect(0, 0, 10000, 10000));
 }

```

# Answer
> 1 votes
Use a bool. Just have a boolean value that gets flipped when the first button is pressed:

```
using UnityEngine;
using System.Collections;![alt text][3]

 public class window : MonoBehaviour
 {
     private bool render = false;
     private bool redWindow = true;
     public Rect windowRect0 = new Rect(20, 20, 120, 50);
     public Rect windowRect1 = new Rect(20, 100, 120, 50);
     void OnGUI()
     {
         GUI.color = Color.red;
         windowRect0 = GUI.Window(0, windowRect0, DoMyWindow, "Red Window");
         if( !redWindow )
         {
             GUI.color = Color.green;
             windowRect1 = GUI.Window(1, windowRect1, DoMyWindow1, "Green Window");
         }
     }
     void DoMyWindow(int windowID)
     {
         if (GUI.Button (new Rect (10, 20, 100, 20), "Hello World"))
         {
              redWindow = false;
         }

         //GUI.DragWindow(new Rect(0, 0, 10000, 10000));
     }
     void DoMyWindow1(int windowID)
     {
         if (GUI.Button(new Rect(10, 20, 100, 20), "Hello World"))
         print("Got a click in window with color2222222222 " + GUI.color);
         //GUI.DragWindow(new Rect(0, 0, 10000, 10000));
     }

```

So, you click the button, and the other one is added to the GUI.

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


# Question
Title: Unity 4.6: Position jumps when switching Canvas render mode from Overlay to camera in code
In the project I am currently working on I have two sets of main UI: one set that is on the screen at all times for the players use, and the second set which the player can open and look at to gauge their progress and see things about the game world(think pokedex) . The second set also has 3d models in front of the UI in places. To achieve this, I have a script that changes the canvas render mode to Screen Space - Camera when the 2nd UI opens, and I instantiate a 3d model in front of it. My problem is when I switch the canvas back to Screen Space - Overlay, it jumps down in the corner.

My to switch the canvas mode to Camera is as follows:

```
 /*--Adjust canvas--*/
     canvas.renderMode = RenderMode.OverlayCamera;
     canvas.planeDistance = canvasPlaneDistance;  //1 in this case

```

My code to switch the canvas back to overlay looks like this:

```
 /*--Adjust canvas render mode and position--*/
     canvas.renderMode = RenderMode.Overlay;

```

I discovered that it seems the problem is because the z pos of the Canvas's Rect Transform changes value when I initially change the render mode and this displaces it when I switch it back. I can adjust it back into position in the code by doing this:

```
canvas.GetComponent<RectTransform>().localPosition =
         new Vector3(canvas.GetComponent<RectTransform>().localPosition.x,
                     canvas.GetComponent<RectTransform>().localPosition.y,
                     0);

```

But this causes a disorienting flicker which I would rather avoid. Is there any workaround or fix for this?

# Answer
Instead of changing the render mode of the canvas you could instantiate the 3d model and a Camera that points at it in an unused part of the scene (or set the Camera culling settings to only render the 3d model). That camera then renders to a texture that is used by an Image element in the alternate GUI.

You'll need Unity Pro though.
> 0 votes

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


# Question
Title: Modular enemy behaviour in a shmup - Delegates unsuitable?
I'm creating a shmup type game and trying to implement the enemy wave system, which includes the associated enemy behaviours like their movement and bullet patterns. I've tried to separate the concerns of each aspect through classes and then eventually linking them together like so (part psuedo code to remove irrelevant pieces) :

```
Class WaveInstantiate {
    private EnemyMovement enemymovement;

    public void MakeEnemy(Vector3 pos, Quaternion rot, Enemy.EnemyMove behaviour) {
        GameObject enemy = Instantiate (ship, pos, rot) as GameObject;
        enemy.GetComponent<Enemy> ().moveEnemy = behaviour;
    }

    public IEnumerator Wave1() {
        // Set spawn spots and no. of enemies
        // Make the calls to: MakeEnemy(pos, rot, enemymovement.SomeFunctionToMoveEnemy)
    }

    public IEnumerator Wave2() // etc
}

```

WaveInstantiate defines the objects that are in the waves. Waves are determined by a GameController keeping track of the waves. There is a `MakeEnemy` function that will `Instantiate` the enemy and apply the movement behaviour that is given from the wave

```
Class Enemy {
    public delegate IEnumerator EnemyMove(Enemy enemy);
    public EnemyMove moveEnemy;

    void Start() {
        // Do some setup

        StartCoroutine(moveEnemy (this));
    }
}

```

The Enemy class is the main class that encapsulates all of the things necessary for the Enemy to function. Will start a coroutine that runs the function that was given to `moveEnemy` delegate by the waveinstantiate class.

```
Class EnemyMovement {
    private BulletPatterns bulletpatterns;

    public IEnumerator ForwardThenBack(Enemy enemy) {
        // Move object forward
        yield return StartCoroutine(bulletpatterns.BulletsAtPlayer (enemy.rigidbody.position));
        // Move object back
    }

    // Define some other movements here also
}

```

A class that defines all of the movement behaviour and controls when the ship will shoot. Makes a call to a BulletPatterns function to determine what kind of bullet pattern this. These functions are used as the delegate implementations for `moveEnemy`

```
Class BulletPatterns {
    private GameObject playerShip;

    public IEnumerator BulletsAtPlayer(Vector3 spawnPos) {
        // Create some bullets that are being aimed at the player
    }
}

```

Defines various types of bullet patterns that may be called independently.

Now my implementation of this structure works, but the problem is when i want to tweak certain movement behaviours. It's natural to parametrise certain things you want to tweak and let the caller handle the values, but since the movement is defined by a delegate, it becomes difficult when certain movement behaviour functions need different parameters to tweak that behaviour. But delegates also provide a nice separation and abstraction away from the movement of any particular enemy; if you want to make some new movement behaviour you can just create a function that handles it and pass in that function to the delegate that handles moving.

Is using delegates like this salvageable in any way or does it require another way of thinking about this?

# Answer
> 1 votes
What I've found more useful in Unity is to really take advantage of editor, and realise the fact that you're working towards a solution that is drag and drop able rather than flexible in code.

An enemy movement in Unity *could* be represented by a single method, but I believe it would be much better, and much more to the style of Unity to have separate components for these different movements. Where you would pass a delegate into a method, you would drag and drop a "Movement" component.

I would start by defining a interface, so we can interface with these components in a common way:

```
public interface IMovable
{
    float   Speed      { get; set; }
    void    DoMove();
}

```

That's obviously very minimal, but it'll do for this example. This is where *DoMove* moves in some way by *speed* amount. This is really the same as the delegate you were using.

So, now we have a common interface, but now what do we do with it? Well, we make more *specific* components. But then we'll face the same problem with parameters as delegates had, right? Well this is where the Unity editor comes in. Let's define a simple *Follow* component that implements *IMovable*.

```
public class Follow : MonoBehaviour, IMovable
{
    public float      speed;
    public GameObject target;

    // Let's provide a Speed property, like we "promised" to IMovable.
    public float Speed
    {
        get
        {
            return speed;
        }
        set
        {
            speed = value;
        }
    }

    // Let's provide a DoMove method, like we also "promised" to IMovable.
    public void DoMove()
    {
        // Move towards the target, if there is one.
        if( target != null )
        {
            Vector3 normal = ( target.transform.position - transform.position ).normalized;
            transform.Translate( normal * Time.deltaTime * speed, Space.World );
        }
    }
}

```

As you can see here, we provide the IMovable interface, but we don't purely rely on the information given to us through it. So, how do you add a target to follow? Drag and drop it from the editor, maybe set target in some code that knows about the true implementation of the interface.

You can go crazy making all these different movement components. All you have to do is drag and drop one onto the object and you have that functionality.

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


title: DirectX Quaternion SLERP Wrong Answer?

text:
# Question
Title: DirectX Quaternion SLERP Wrong Answer?
I have some code that looks like this:

```
DirectX::XMVECTOR a, b, c;
a = DirectX::XMQuaternionIdentity();
b = DirectX::XMQuaternionRotationAxis(DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f), 3.1415f);
c = DirectX::XMQuaternionRotationAxis(DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), (3.1415f * 3.0f) / 2.0f);

DirectX::XMVECTOR slerpAB = DirectX::XMQuaternionSlerp(a, b, 0.4f);
DirectX::XMVECTOR slerpBC = DirectX::XMQuaternionSlerp(b, c, 0.85f);
DirectX::XMVECTOR slerpCA = DirectX::XMQuaternionSlerp(c, a, 1.0f);

```

The thing is, I'm *sure* that slerpBC is wrong. Here's what I'm getting:

If I understand it right, slerpBC should be 85% of the way towards a 3-quater turn around the Z axis. But when I plug that value in to Wolfram Alpha, it looks totally wrong.

Furthermore, when I run the code through my own Slerp code I get a totally different answer that looks more correct, to me.

So... What am I doing wrong?

# Answer
> 2 votes
The quaternion you find using your method is indeed correct.

However, it’s also pretty unlikely that `DirectX::XMQuaternionSlerp` would behave incorrectly with such trivial input.

Thus, I suspect that the thing you are doing wrong is:

* trusting what you see in the debugger while running potentially optimised code
* assuming the layout of a `__mm128` would be the {W,X,Y,Z} of your quaternion (DirectX quaternions are stored as XYZW so the value you plugged into Wolfram Alpha was `X + Yi + Zj + Wk` anyway)

So, use `XMVectorGetX(slerpBC)` to get and print the `X` value of your quaternion instead, you’ll see whether it matches what the debugger says.

# Answer
> 2 votes
By design, DirectXMath returns for `XMQuaternionSlerp` the same result as you'd get from the following (inefficient used only for testing) scalar code:

```
XMVECTOR ScalarQuatSlerp(XMVECTOR q1, XMVECTOR q2, float t)
{
    // Extract the components
    float q1x = XMVectorGetX(q1);
    float q1y = XMVectorGetY(q1);
    float q1z = XMVectorGetZ(q1);
    float q1w = XMVectorGetW(q1);
    float q2x = XMVectorGetX(q2);
    float q2y = XMVectorGetY(q2);
    float q2z = XMVectorGetZ(q2);
    float q2w = XMVectorGetW(q2);
    // Find the dot product
    float dot = (q1x * q2x) +
        (q1y * q2y) +
        (q1z * q2z) +
        (q1w * q2w);
    // Determine the direction of the rotation.
    if (dot < 0.0f) {
        dot = -dot;
        q2x = -q2x;
        q2y = -q2y;
        q2z = -q2z;
        q2w = -q2w;
    }
    float theta = acosf(dot);
    float sintheta = sinf(theta);
    float scale1 = (sinf(theta*(1.0f-t)) / sintheta);
    float scale2 = (sinf(theta*t) / sintheta);
    // Perform the slerp.
    q1x = (q1x*scale1) + (q2x*scale2);
    q1y = (q1y*scale1) + (q2y*scale2);
    q1z = (q1z*scale1) + (q2z*scale2);
    q1w = (q1w*scale1) + (q2w*scale2);
    // Convert the scalar answer to a vector
    XMVECTOR r = XMVectorSet(q1x,q1y,q1z,q1w);
    return r;
}

```

which is derived from the classic quaternion paper: Shoemake, Ken. "Animating Rotation with Quaternion Curves", Compute Graphics (SIGGRAPH 1985), Volume 19, Number 3, 1985.

You should read Jonathan Blow's The Inner Product, April 2004 article on slerp: Understanding Slerp, Then Not Using It. Basically, for most applications you shouldn't use `XMQuaternionSlerp`. Instead use 'nlerp' which is implemented in DirectXMath as:

```
XMVECTOR r = XMVectorLerp( q1, q2, t );
r = XMQuaternionNormalize( r );

```

---
Tags: c++, directx, quaternion
---


title: Could this MMORPG project-model work?

text:
# Question
Title: Could this MMORPG project-model work?
This is an extension of my previous question.

Recently I had an idea of making an, as I could describe it, agile open-source player-financial-profitable MMORPG, which has an interesting (from my POV) project and development model.

Agile means that development should be iterative, with world extending every fixed period of time. And maybe even game universe\plot may be based on iterative development.

Open-source means that everybody can participate, but, obviously, I wish to establish some kind of core team. I estimate that about 0,01% of players will contribute. And this is where I want to make the number grow to about 0,1%.

That's third part: player-financial-profitable means that every player that has outgrown some reputation ceiling (level or another kind) could contribute some kind of \*thing to the game. I think about *things* as *special items* for now, but they could be transformed into anything on later architecture stage. *Special items* can be obtained without any financial donations, of course, but if one player wish to buy it from another, it should be sold for real money, presented as some special "platinum coins" in the game. Money should be parted between solder and creator of the item.

But there is one rule — the item, that one creates, must be unique. Under unique I mean unique. It should have unique look, unique animation, and, most importantly, unique ability, that was not presented by any other item so far, not just exterminator sword with +10000 damage. And unique ability should be coded and designed uniquely. That means, that if creator player is not a one-person collaboration between designer and programmer, he should appeal to off-site labour, or to the core team itself. Working places are created and everybody is happy.

So, that is the model as I see it now (and I invented it yesterday night). The main question is:

**1) Should I even bother?** The idea is so ambitious, that could be interpreted as flying in the sky with the help of no wings. And I don't want to spend next ten years of my life (that's the minimum period in which I expect the project to become successful) working on unfortunate from the beginning project.

I have many other questions, but this text already gone too big, so I'll ask only most important:

2) Isn't there some similar game project-model already? I've seen PlaneShift, but they definitely aren't what I'm talking about.

3) Are open-source practices suitable for game development? There are so few good professionals in the field, will they bother to contribute?

4) On how many people should I count on early development stage? Later?

5) How to do all this thing without any reasonable budget?

6) Where do I begin without XP in game development, but with XP in programming per se?

**Note to moderators**: Please make this community wiki, I don't see my checkbox.

# Answer
> 11 votes
> "Should I even bother?" + "Where do I begin without XP in game development"

Sorry, but the simple answer is No

The long answer is that MMO's are the hardest possible type of game to develop, with open-world titles being the only other thing close to as difficult. They often take teams of several hundred people with a wide range of skills, massive costs in server/back-end investments, and an ludicrously large amount of content.

The development scene is littered with teams filled with people with over a decade of experience in game development who tried and failed to build an MMO. Realtime Worlds being the most recent, and painfully expensive ($100m down the drain for APB) example.

There are some exceptions if you set your sights low enough. Text/webpage based MMO's like Urban Dead or the various projects from Gameforge are in theory, buildable by a single individual or a small group of people. These games are mostly giant databases with a pretty web interface.

This doesn't even address the inherent security issues of a P2P financial economy paired with open source development which is a recipe for extreme direct financial griefing.

**Don't be discouraged though**

If you really want to learn how to make games that's great, and right now is one of the easiest times in the world to both build games and distribute them to people. You've got the indie channel of XBLA, iPhone app stores, Facebook, Flash portals. All of which are fantastic places to start and don't require you to spend either the time, money, or find the people needed to make a big project.

I encourage you to build games, but start small.

# Answer
> 3 votes
Seems like none of the stuff you listed: financing, player-participation, "unique" items really get at the issue of whether your project is worth pursuing.

Is the game fun?

If yes, go. If no, don't.

All that stuff would be neat. Really! But honestly, it's fairly minor details. Or am I missing something?

# Answer
> 2 votes
This "unique" you're talking about is just plain foolishness.

Let's say you somehow manage to build this game (you won't, as wkerslake pointed out).

1) it doesn't scale. If your player base grows, you'll have to hire more and more artists just to create tons of "unique" arts. Add up the time the design team will spend creating the stats and name for these objects.

2) if you do all this work for just a single unique item, *of course* it means that you expect to gain from selling it enough money to repay its cost. Uh, no, you're giving them for free. WTF, lol.

3) if a player stops playing, the unique items he has are "lost" to the game. And since the game is supposedly played by tons of people, most people won't ever see most items. This smells of pointless to me. You have assets: use them! Don't hide them!

# Answer
> 0 votes
I love the idea of an incremental development approach. Many games have gone to a season-based model, and some (try to) have a monthly new bonus mission, to keep players coming back regularly. I could see something like that, where each project the developer has to perform is smaller, and thus hopefully easier to plan and pull off, being useful in reducing the risk and up-front investment of keeping the service running. (That said, the voices here are right in that an MMORPG combines pretty much all the problems you can have in programming into one app, so there will be a major up-front investment to even get started with the first mission)

I'm not quite sure of the point of the item design process, though. If I understand you correctly, you're essentially open-sourcing the easy, inexpensive parts, and the ones that need to be coordinated for gameplay impact.

Everything that involves manual labor is expensive, especially because it takes much longer to create something than to consume it. Which is why most MMORPGs have some form of grinding, levelling and procedurally generated encounters to while away the time until the next manually generated content is finished.

You seem to be keeping all the stuff that needs a budget and is difficult, or thinking you can "offshore" them to make them cheaper. If it was so easy to outsource graphics artists, I'd think the big MMORPGs would already be doing it. It's hard to communicate with designers and keep a design coherent across multiple designers.

Shouldn't you be doing it the other way around? I could see people submitting their own small art assets for items, using an animation builder to tinker out the look and colors, creating their own missions. Maybe you could have a sort of "contest" where people who generate nice assets get the assets integrated into the game as part of missions or loot drops, and the ones who don't win can use their items as vanity items in social zones.

But given how difficult balancing out item stats is, and how important it is that nobody take advantage of this (because it affects other players, not just the one making the item), I would leave that to your designers. Maybe provide a pre-built class of stats for testing or so, maybe with a UI that lets you customize stats within strict limits, so it's impossible to make an unbalanced item. Similarly, you could make the weapon designs based on a construction kit-like approach, where you can combine different weapon parts and color them or texture them within limits.

Still, you'd have manual labor even then, because someone needs to review all the submissions, not just for quality, but also to make sure nobody just steals art assets from somewhere and submits them.

---
Tags: mmo, open-source, project-management, business-model
---


# Question
Title: Who Handles Collision in a Component Based Entity System
I kind of stucking at my current plattformer protoype for learning the component based entity system pattern.

I have CollisionComponent and a CollisionSystem. The CollisionSystem checks every frame all entities with CollisionComponents for intersection. Then it marks inside the CollisionComponent the entities which are colliding with this entity. So if an entity A collides with Entity B then they both have a the other as a reference inside their CollisionComponent as data.

This works absolutely fine and I can tell which entity is colliding with something/someone.

Now I have the problem how to use this information properly. I have a MovementSystem and it moves entities with a MovementComponent based on the velocity and the acceleration.

Who is now responsible for NOT moving a entity or do something else on a collision. Should the MovementSystem check if the entity has a CollisionComponent and if there is one, should the MovementSystem handle the NOT movement?

Let's say I have this situation. I have an entity (player) with a MovementComponent and a velocity to the right (because the player presses the right arrow) and the usual downwards velocity due of gravity influences. The player entity collides with another entity. A GroundComponent entity. Now which system should put entity A (the player) upwards so that he does not colliding with the ground anymore? The MovementSystem? At the same time, the player entity collides with another entity, an enemy. Which system should now handle the damage, or the knockback or whatever that enemy does to a player unit?

I really like the CBES but it really does not get into my mind how everything glues together.

I want to threat the components as pure data, so no logic in there (besides of ScriptComponents, but this is another type of problem)

Now my question is, which system handles which cases and how to treat passes of system (e.g. Movement pass one then the other systems then movement pass 2 and so on? How many systems do I really need and should a system only handle one type of problem? MovementSystem -\> pure movement no matter what. CollisionSystem -\> pure collision registration no matter what, DamageSystem -\> damage handling based on component data

# Answer
I'll try to explain with an example:

Let's say we have an RPG where you can enchant your weapons with elemental damage. The weapon still have a "physical" attack power, which is reduced by the enemies "phyical armor". But now we have elemental damage, and thus the enemies might have elemental resistances.

This is perfect for Entity Component System, because we can normally attach WeaponComponents on the weapon to describe physical damage, and ArmorComponents on the enemies to describe physical defense. To add the elemental mechanics, we simply add the elemental counterparts of the Weapon and Armor Components and Systems.

Thus, when resolving the damage of an attack, both Weapon/Armor and Elemental/Resistance components and systems will add gross damage to the net, final damage dealt.

In regard to your Movement/Collision problem, I would try to make a "MovementBlockingCollisionSystem", where the system will check for collisions and the direction of collision and hard set the position of the entity in a way it will be right on the collision surface without overlapping with it. You might still want to keep your CollisionSystem so you can check for collisions without blocking movement (useful for triggers or "ghost" enemies).

By the end of the day, it all really depends on how you model your data and how willing you are to write several, specialized Systems.
> 4 votes

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


# Question
Title: How to implement 2d collision detection that is immune to low framerate and fast movement?
I am trying to implement my own collision detection for a 2.5d voxel style platformer using Three.js. I have a problem with my implementation - if the framerate is too low or the character is moving too fast (usually when falling from high places) it falls right through. Is there a way to improve collision detection to be immune to problems like this?

This is how I detect collisions:

```
function render(){
    requestAnimationFrame(render);

    setVelocity();
    animate();
    manageCollisions();

    renderer.render(scene, camera);

```

}

```
function manageCollisions(){
//Check every game object for collision -> TODO: implement broad phase when dealing with many objects
for(i=0; i < world.length; i++){

    //Check for bottom collision <- ALWAYS check (unless moving up)
     if(velocityY<0) {
        if( (character.position.y - character.height/2) < (world[i].position.y + world[i].height/2)
            && (character.position.y + character.height/2) > (world[i].position.y + world[i].height/2)
            && (character.position.x + character.width/2) > (world[i].position.x - world[i].width/2)
            && (character.position.x - character.width/2) < (world[i].position.x + world[i].width/2))
        {
            console.log("bottom collision " + i);

            velocityY=0;
            jumped=false;
            grounded = true;

            character.position.y = world[i].position.y + world[i].height/2 + character.height/2 - 0.1; //-0.1 prevents shaking
        } else {
            grounded = false;
        }

    }

    //Check for right collision <- ONLY if moving right (velocityX is positive)
    if(velocityX > 0){
        if( (character.position.y) < (world[i].position.y + world[i].height/2)
            && (character.position.y + character.height/2) > (world[i].position.y - world[i].height/2)
            && (character.position.x + character.width/2) > (world[i].position.x - world[i].width/2)
            && (character.position.x - character.width/2) < (world[i].position.x - world[i].width/2))
        {
            console.log("right collision" + i);
            velocityX=0;
            character.position.x = world[i].position.x - world[i].width/2 - character.width/2;
        }
    }

    //check for left collision <- ONLY if moving left (velocityX is negative)
    if(velocityX < 0){
        if( (character.position.y) < (world[i].position.y + world[i].height/2)
            && (character.position.y + character.height/2) > (world[i].position.y - world[i].height/2)
            && (character.position.x - character.width/2) < (world[i].position.x + world[i].width/2)
            && (character.position.x + character.width/2) > (world[i].position.x + world[i].width/2))
        {
            console.log("left collision" + i);
            velocityX=0;
            character.position.x = world[i].position.x + world[i].width/2 + character.width/2;
        }
    }

    //check for top collision <- ONLY if moving up (velocityY is positive)
    if(velocityY > 0){
        if( (character.position.y + character.height/2) > (world[i].position.y - world[i].height/2)
            && (character.position.y - character.height/2) < (world[i].position.y - world[i].height/2)
            && (character.position.x + character.width/2) > (world[i].position.x - world[i].width/2)
            && (character.position.x - character.width/2) < (world[i].position.x + world[i].width/2))
        {
            console.log("top collision" + i);
            velocityY=0;
            character.position.y = world[i].position.y - world[i].height/2 - character.height/2;
        }
    }

}

```

}

# Answer
> 1 votes
## Overview

Essentially I think your talking about the problem where objects move to far in a single update step thus allowing them to seemingly pass through walls. This is a common problem, but an understandably irritating one for the player - although sometimes it's fun.

## Direct Solution

The most direct way of answering your question I can think of is to somehow specialise your collision detection/physics simulation to detect collisions for the entire space occupied by the shape over the last frame.

This sounds complicated because it is.

Essentially, you need to first be able to define a better path of traversal for your object. If you're using something like an euler interator for position then the movement is a straight line per-frame. This is probably not accurate enough since you missed a few frames, so you need another method to calculate the actual path taken by the object over the last frame.

Once you have this, you need to take the bounding shape used in collision detection and extrude it along this path, resulting in a new shape which encompasses all space occupied by the object over the last frame.

Then detect collisions with this, work out the new path of the object post collision and repeat until the object's movement has been simulated for a long enough period.

This solution, while accurate, is probably impractical, prone to failure, hard to write and will probably be such a drain on resources that it will cause more slowdown than before.

## Easy Solution

The easiest way is to fix your timestep. The linked article discusses a way to setup your game-loop such that you always get your updates in fixed timesteps while rendering frames at the highest rate possible on the current machine.

With a fixed timestep you are somewhat immune to the effects of framerate drops. If a frame takes longer, you get more update steps. It isn't immune to objects moving to fast, but that can be fixed by capping the maximum speed of some objects or using smaller time steps.

---
Tags: collision-detection, javascript, platformer, 2.5d, three.js
---


title: Create player rankings?

text:
# Question
Title: Create player rankings?
I recently created a tournament system that will soon lead into player rankings. Basically, after players are done with the tournament, they are given a rank based on how they did in the tournament. So the person who won the tournament will have the most points and be ranked #1, while the second will have the second most points and be ranked #2, and so on...

However, after they are ranked in the new rankings, they can challenge other members and have a way to play other members and change their rank. So basically (using a ranking system), if Player A who is ranked #2 beats Player B who is ranked #1, Player A will now become #1.

I've also decided that if a player wants to compete in the rankings but was not present during the tournament, they can sign up after the tournament, and will be given the lowest possible rank with the lowest score (but they have a chance to move up).

So now, I am wanting to know which way should I go about planning this. When I convert the players from tournament to match rankings, I have to identify them with points. I decided I can do this 2 ways:

```
1  1000
2  900
3  800
4  700
5  600
6  500
7  400
8  300
9  200
10 100

```

Or I can have it set up in a exponential type of system where the points will be greater in between the players that are ranked higher.

After looking on the internet I've decided it would be wise to use ELO to give players their new rank after they players have matched against each other.. I went about it on this page: http://www.lifewithalacrity.com/2006/01/ranking\_systems.html

So if I go about this my first way, and lets say I have rank #10 facing rank #1. My formula is:

```
R' = R + K * (S - E)

```

and the rating of #10 only has 100 points where #1 has 1,000. So after doing the math rank #10's expected value of beating #1 is:

```
1 / [ 1 + 10 ^ ( [1000 - 100] / 400) ]
= 0.55%

```

So 100 + 32 * (1 - 0.52) = 115.36

The problem I have with ELO is it makes no sense. After A rank such as #10 beats #1, he should not only gain something as low as 15 points. I'm not sure if i'm doing the math wrong, or if I'm splitting up the points wrong. Or maybe I shouldn't use ELO at all?

# Answer
> 1 votes
An Elo-type system is designed to reflect a game where the #1 person is not expected to win every single match. A #1 ranked chess player might only beat the #10 ranked player 8 out of 10 times. The #1 ranked player is still better than the #10 ranked player but if you happen to observe only one of the 2 in 10 that the #10 ranked player won you wouldn't know that.

You can also tweak the variables in the Elo formula to make the outcome a single match have more or less impact on a player's score. "**K**" in that formula is the most a player's score can change in a single match. That is why you are seeing such a small change in score for a single match, the most the score could possibly change in your formula is 32. Also you are doing the math wrong, the #10 ranked player should be: `100 + 32 * (1 - 0.0055) = 131.824`; they should get almost all of the 32 points up for grabs in that match because the expectation they would win was so low.

That 400 number should also be adjusted to your game. Using 400 assumes a player ranked 100 points higher wins 64% of the time. 400 in particular comes from chess, you might want to adjust this number as you observe the variability in your particular game. For instance, using 300 would mean a player ranked 100 points higher is expected to win 68% of the time and 1 would mean the higher score player is virtually always expected to beat the lower score player.

Newer systems like Magic's "Planeswalker Points" also involve a participation bonus to prevent high ranked players from simply not playing to protect their rank.

---
Tags: game-design, algorithm, multiplayer
---


# Question
Title: Why does resizing my game window move and distort my rendering?
I'm starting to make a game, and the first screen I've made is a very simple loading screen with some centered text.

On starting it up, the text is nicely centered:

Then I resize the window, and I get:

Why is it stretched? And why has it moved? Looking at my code it looks like everything should be perfectly centered:

```
public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0.2f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (Assets.manager.update()) {
            // Eventually change to a main menu or something
        }

        String text = "Loading " + Math.round(Assets.manager.getProgress()) + "%";

        BitmapFont.TextBounds bounds = fnt.getBounds(text);

        batch.begin();
        fnt.draw(batch, text, (Gdx.graphics.getWidth()/2)-(bounds.width/2), (Gdx.graphics.getHeight()/2)-(bounds.height/2));
        batch.end();
    }

```

# Answer
I'm not sure if a more specific answer is needed here, but for me to fix this issue I had to adjust the projection matrix on the SpriteBatch. Although destroying the SpriteBatch and recreating it would also work.

So in my constructor I create the camera:

```
camera = new OrthographicCamera();

```

Then when the size of the window changes I execute:

```
camera.setToOrtho(false);
batch.setProjectionMatrix(camera.combined);

```

The first line causes the camera to recalculate the matrix for the new width/height of the window, and the second line sets the batch's projection matrix to be the same as the cameras, which the origin in the lower left corner.

Another option I suspect would work would be to use:

```
Matrix4 matrix = new Matrix4();
matrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(matrix);

```

If you wanted to specifically set the the coordinates of the origin.
> 4 votes

# Answer
When you resize a window that you are rendering to, you generally also need to adjust the rendering viewport bounds and potentially the bounds of any intermediate render targets (depending what you are doing with them).

In OpenGL, you can make use of the `glViewport` function to handle the viewport adjustment. Update it when your window size changes. The values of the graphics API's viewport are used to compute the window-space coordinates of your rendered geometry prior to the rasterization of that geometry, if your viewport bounds (and again, potentially render target bounds, depending) do not match the physical bounds of your window, you'll get distorted results.

If you have any intermediate render targets to resize, this is usually more involved, and usually means having to destroy and recreate the render target at the appropriate size *or* maintaining a separate set of bounds information allowing you to reuse the target if you decrease the render target size and keep reusing it as long as you don't expand beyond the original (at which case you reallocate and update the bounds). This also may require some clamping on your part within your rendering.
> 2 votes

---
Tags: libgdx, window-management
---


# Question
Title: How do I avoid going through objects at high speed?
I am quite the beginner in XNA. I have only recently started using GameComponents. I have a multiplayer game called Better Pong. I move the ball (which is an object) by incrementing the Vector2 (the position) of the ball by the velocity Vector2 and updating the hitbox Rectangle.

However, by having very large speeds (such as (12,12)) the ball might go through the paddle since it just skips through the Paddle's Rectangle "hitbox".

Is there a way to make the ball make smaller movements, so it doesn't go through the paddle (but still move fast)?

# Answer
You need to either interpolate or extrapolate the collision. Basically this means instead of just checking the collision of the object where it is NOW, check the collision of the object with where it is and where it WILL BE or WAS, then check x number of times in between those positions.

```
Vector2 pos = ball.position;
Vector2 prevPos = ball.previousPosition; // You'll have to keep track of where the ball was 1 frame ago.

for (int i=0; i<COLLISION_PRECISION; i++)
{
    Vector2 testPos = lerp(prevPos, pos, i/COLLISION_PRECISION);
    if (PointInsideRect(testPos, paddleRect))
    {
        ball.position = testPos;
        // Do any collision reactions
        break;
    }
}

```

In this example, you'd check for collisions from where the ball was last frame to where it currently is, and a number of points in between those points equal to COLLISION\_PRECISION. The higher the COLLISION\_PRECISION, the less chance your ball will move through a paddle.

EDIT: I forgot to mention, this is pseudo code, you shouldn't be copy pasting it or anything, it's just kind of an outline of what you have to do.
> 1 votes

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


# Question
Title: Unity Android Orientation Bug in Auto Rotate
I am currently looking for a workaround, or fix, for a Unity bug.

I want to be able to auto-rotate my game, while respecting the Android system settings.

Currently, if you set your Unity Orientation Mode to "Auto Rotation", your application will automatically change its orientation based on the physical's device orientation. In iOS, if you disable the Screen Rotation in device settings, the auto rotation stops as intended. In Android, even if you lock your screen orientation, the application will continue to auto rotate. This is a major bug.

Does anyone know of a workaround, so that my android application will be able to auto-rotate, while still respecting the device system settings?

You can easily reproduce this bug by creating a blank project, setting the orientation mode to "auto rotation" and running it on an android device.

# Answer
> 2 votes
This is a major bug in Unity. For those who are stumbling here trying to find a solution, a very awesome gentlemen posted a fix over here at github

https://github.com/hvs-clark/unity-android-rotation-lock

Hopefully Unity fixes this crazy bug soon, so we don't have to use workarounds like this in the future. From what I read, it is by design, which in my opinion is horrible design. https://github.com/hvs-clark/unity-android-rotation-lock

---
Tags: unity, android, orientation, bug, rotate
---


# Question
Title: Problem setting up OpenGL dev environment in Ubuntu 14.04
Currently I'm using this tutorial to get started with opengl.So when I try to compile the example program :

```
#include <GLFW/glfw3.h>
#include <thread>

int main()
{
    glfwInit();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    glfwTerminate();
}

```

using

> g++ test.cpp -o test -lglfw3

to ensure that all is good with glfw I get this

> In file included from /usr/include/c++/4.8/thread:35:0, from test.cpp:2: /usr/include/c++/4.8/bits/c++0x\_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options. #error This file requires compiler and library support for the \ ^ test.cpp: In function ‘int main()’: test.cpp:7:10: error: ‘std::this\_thread’ has not been declared std::this\_thread::sleep\_for(std::chrono::seconds(1)); ^ test.cpp:7:38: error: ‘std::chrono’ has not been declared std::this\_thread::sleep\_for(std::chrono::seconds(1));

So then I guessed I could use the flag that g++ suggested and compile it using

> g++ -std=c++11 test.cpp -o test -lglfw3

But then things get weirder and g++ comes with this error(I will post only a part of it since it's a huge output overall but you will probably get the idea) :

> x11\_window.c:(.text+0x2d9): undefined reference to `XSaveContext'
>  x11_window.c:(.text+0x324): undefined reference to` XChangeWindowAttributes' x11\_window.c:(.text+0x3be): undefined reference to `XSetWMProtocols' x11_window.c:(.text+0x417): undefined
>  reference to`XChangeProperty' x11\_window.c:(.text+0x41c): undefined reference to `XAllocWMHints' x11_window.c:(.text+0x48e): undefined
>  reference to`XSetWMHints' x11\_window.c:(.text+0x49d): undefined reference to `XFree' x11_window.c:(.text+0x4a2): undefined reference
>  to`XAllocSizeHints' x11\_window.c:(.text+0x5ed): undefined reference to `XSetWMNormalHints' x11_window.c:(.text+0x5fc): undefined reference
>  to`XFree' x11\_window.c:(.text+0x613): undefined reference to `XAllocClassHint' x11_window.c:(.text+0x66c): undefined reference to` XSetClassHint' x11\_window.c:(.text+0x67b): undefined reference to `XFree' x11_window.c:(.text+0x6dc): undefined reference to` XISelectEvents' x11\_window.c:(.text+0x71e): undefined reference to `XRRSelectInput' //usr/local/lib/libglfw3.a(x11_window.c.o): In
>  function`hideCursor': x11\_window.c:(.text+0x7bd): undefined reference to `XUngrabPointer' x11_window.c:(.text+0x7fb): undefined reference to` XDefineCursor' //usr/local/lib/libglfw3.a(x11\_window.c.o): In function `captureCursor': x11_window.c:(.text+0x880): undefined
>  reference to`XGrabPointer' //usr/local/lib/libglfw3.a(x11\_window.c.o): In function \`showCursor':

How could I fix this type of problem cause it really hurts my motivation to get into opengl. And please if you have in mind any better-hassle free guide for setting a proper opengl environment for deving with glfw and glew in linux/ubuntu , care to mention it.

UPDATE 1: http://pastebin.com/CPEwmbUZ \<--- The whole output is here if anyone cares.

# Answer
Error `undefined reference` means that linker can't find function's definition. Probably, you should link X11 library to your program by console parameter `-lX11`. So, it should be `g++ -std=c++11 test.cpp -o test -lglfw3 -lX11`. I think you should link OpenGL library too (by `-lGL`).
> 1 votes

---
Tags: opengl, linux
---