# Question
Title: Imageeffects: No need for Framebuffer? Just use Textures and Shaders?
I am doing simple Image Effects, and always i see in examples, that people are binding textures to framebuffers. Why can't i just use textures?

So the process would be.

1) Input Texture 2) Shader: Do Processing on this Shader 3) Render to the same Texture

So no need for framebuffer? This step is done completely linear...no off-screen rendering. So cani say that i don't need a framebuffer in this scenario?

thanks!

# Answer
There seems to be a bit of a conflation of naming and the meaning of the names.

When you want to write data from a fragment shader, you use a *framebuffer* object (FBO) with zero or more *render targets* attached as *attachments*. Those render targets can be either *renderbuffer* objects or *textures*.

The workflow you have with the traditional pipeline to generate something into a texture is:

* bind output render targets into a framebuffer object and make it active;
* bind all the input textures into your shader program and set all your uniform parameters;
* draw a "full screen" rectangle (two triangles) in such a way that it exactly fills the viewport dimensions;
* in each fragment that this generates, the fragment shader will run and produce an output fragment.

If you have several steps of operations you need to do, it's common to use several textures and bounce between them in a *ping-pong* pattern.

Since OpenGL 4.2 or so, a non-coherent function 'imageStore' lets you write to arbitrary areas of a bound texture from inside a shader, typically when executing a compute shader.
> 1 votes

---
Tags: opengl, image-effects
---


# Question
Title: How does a developer ask for the rights to use a character?
What channels must a developer go through to ask for the rights to a character? I want to make a point and click adventure based on Freddy Krueger, and I know my chances are slim, but how do you even go about asking?

# Answer
> 4 votes
Have your people call their people.

You need to find contact information for the appropriate business/legal department (or person) within the organization that holds the intellectual property rights that you want to license. This can be a single person, in a smaller studio, to an entire department (at a large publisher for example). This may be difficult to do because that information isn't always readily made available on a company's website: you may need to resort to calling reception and asking to be put in contact with the appropriate person, or mining some industry contacts you may have to arrange a meeting.

Note that you can expect a prolonged series of discussions and meetings, during which you will likely need to discussion with the IP holder many of the details of your project, your financials (current and future projections based on your use of the IP) and many other business tidbits. This is a business deal, after all.

If you don't have your own business/legal representative, consider retaining the services of some kind of lawyer for the purposes of brokering the deal. They are likely to be far more knowledgeable than you in the details of IP law and the associated licensing agreements: you are *extremely unlikely* to get a blanket, informal "sure use our characters" grant of permission from a savvy IP holder. You're more likely to end up negotiating some kind of contract, where they grant you some limited use of their IP in exchange for some combination of money, share, control over your project, et cetera.

---
Tags: character, copyright
---


# Question
Title: Why does my collision detection code cause my framerate to drop?
I have this code:

```
foreach (CollisionTiles tile in map.CollisionTiles)
{
  player.CollisionBox(tile);
  foreach (Enemy enemy in enemys)
    enemy.CollisionBox(tile);
}

```

This is the `CollisionBox()` function:

```
public void CollisionBox(CollisionTiles tile)
{
  int x = rectangle.X / Map.Size;
  int y = rectangle.Y / Map.Size;
  int tileX = (int)tile.Position.X;
  int tileY = (int)tile.Position.Y;

  if (tileX >= x - 1 && tileX <= x + 2 && tileY >= y - 1 && tileY <= y + 3)
  {
    Collision(tile.Rectangle, Map.Width, Map.Height);
    tile.Collide = true;
  }
}

```

These two lines *appear* to be the problem:

```
 int x = rectangle.X / Map.Size;
 int y = rectangle.Y / Map.Size;

```

I guess because it loops through them on every tile...

The Collision() function just check the face's of the two triangles (both player/enemy and the tiles) with these functions:

```
 public static bool TouchTopOf(this Rectangle r1, Rectangle r2)
 {
   return (r1.Bottom >= r2.Top && r1.Bottom <= r2.Top + (r2.Height / 2));
 }

public static bool TouchBottomOf(this Rectangle r1, Rectangle r2)
{
  return (r1.Top >= r2.Bottom - (r2.Height / 2));
}

  public static bool TouchLeftOf(this Rectangle r1, Rectangle r2)
  {
  return (r1.Top <= r2.Bottom - (r2.Height / 2) &&
          r1.Bottom >= r2.Top + (r2.Height / 2) &&
          r1.Right >= r2.Left &&
          r1.Right <= r2.Left + (r2.Width / 4));
  }

  public static bool TouchRightOf(this Rectangle r1, Rectangle r2)
  {
    return (r1.Top <= r2.Bottom - (r2.Height / 2) &&
            r1.Bottom >= r2.Top + (r2.Height / 2) &&
            r1.Left >= r2.Right - (r2.Width / 4) &&
            r1.Left <= r2.Right);
  }

```

When there is more then one monster with the player I get a massive FPSdrop, and it's getting worse when more monsters get added. What should I do to fix that problem?

# Answer
You are checking each object against each collision tile, even when those are too far away to have a chance to affect it. That's inefficient, because the computational cost increases quadratical with the amount of objects. Divide your map into zones and keep track of which zones each mobile object touches. Then only check for collisions inside each zone.

Keeping track of which zones each object touches can be done whenever that object is moved. Compare its old coordinates with the new ones to find out from which zones the object needs to be removed and to which zones the object is added. Each map zone would have a `HashSet<MobileObject>` representing its current inhabitants. Note that when an object is on the border of two zones, it can be in multiple zones at the same time.

When you check for collisions, you only check for collision of objects and tiles which are in the same zone (you might have to check adjacent zones too, when objects are large enought to span multiple zones).

I also assume (but might assume wrong), that you have a lot more collision tiles than mobile objects. When that assumption is right, most zones will always contain collision tiles, but will often not contain any mobile objects. In that case it would be better to iterate all objects and check them against the tiles in their zone instead of the other way like you are doing right now (iterate tiles and check them against mobile objects).

Regarding how to define zones: The most straight-forward way would be to use square-shaped zones of uniform size. This has the advantage that finding out the zone a point is in is trivial: Put the zones in a two-dimensional array. To get the array-indexes of the zone a point is in, just divide the x- and y-coordinate of the point by the zone-size and you have them.

The ideal zone-size depends on your object-density and object-mobility. You will need to find a compromise between keeping the zones small enough so their population is small and large enough to avoid too frequent zone-changes.

When you have areas which are always much more densely-populated than others, it might make sense to divide these areas into smaller zones.
> 1 votes

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


title: Java : 2D Sidescroller Terrain

text:
# Question
Title: Java : 2D Sidescroller Terrain
Okay so After all this Edits here is the main question. How I can generate Terrain with a 2d Simplex Noise Algorithm, I am deletng old info so the post its more readble. I´ve been doing some tests and here are my results so far. Any help is appreciated. Any Ideas why my code isnt working?

I am far from getting a good result, Here is an Image, I am using The Simplex Noise genrator Timothy oferred to me (thanks :D)

And Heres is the Code:

```
public void GenerateChunk(float offsetX, int amplitude, long seed)
{

    // Its += 16 Because each block is 16 pixels
    for(int x = 0; x < CHUNK_SIZE * CHUNK_SIZE; x += 16)
    {
            PerlinNoise.genGrad(seed);
            float height = (float) PerlinNoise.noise(x, 0);
            System.out.print(height);

            for(int y = 0; y < height * 16; y += 16){

                try {

                    Block B = new Block(Material.DIRT, x, y + 400, new Image("res/Dirt.png"));
                    Blocks.add(B);
                    B.setVisible(true);

                } catch (SlickException e) {

                    e.printStackTrace();

                }

            }

     }
}

```

Here its where I call it

```
world.getChunk(0, 0).GenerateChunk(4, 12, 1231233876); // 12312 etc is a test number for the seed.

```

Finally here is the example output (height value)

```
0.0-0.3244323-0.4746854-0.6980603-0.212961030.437604370.0-0.013018643-0.3333134-0.49871972-0.498743-0.226263150.43900093-0.305881470.026026215-0.341923240.0-0.3244323-0.4746854-0.6980603-0.212961030.437604370.0-0.013018643-0.3333134-0.49871972-0.498743-0.226263150.43900093-0.305881470.026026215-0.34192324

```

# Answer
> 0 votes
A few things come to mind :

First off, you're generating noise, but you're using the wrong functions of the noise generator in order to have things like a seed.

The second thing, is that because of the way you generate your chunks, you're not keeping track of the offset of the chunk you're generating, resulting in the same bit of terrain being repeated continuously.

Lastly, you can "scale" perlin noise, making the output seem smoother. this especially works if you're generating "blocks" like you're doing.

You should be using something like this:

```
float persistence = 0;
float octaves = 1; //<-- higher octaving means more detailed terrain
float terrainScale = 10; // <-- higher scale means bigger, seemingly smoother terrain

//offsetX is the highest X value of the LAST chunk + 1
public void GenerateChunk(float offsetX, int amplitude)
{

    GenerateEmptyChunk();

    // Its += 16 Because each block is 16 pixels
    for(int x = 0; x < CHUNK_SIZE * CHUNK_SIZE; x += 16)
    {
            float height = (float) PerlinNoise.PerlinNoise1D((offsetX+x)/terrainScale, persistence, octaves);

                //this is also far from optimal, but i'm sure you can come up with something better.
                for(Block B : Blocks)
                {
                    if(B.getX() == x)
                    {
                    //  System.out.print(B.getX() + "Block");
                        B.setY((int) (400 + (height * amplitude)));
                        B.setVisible(true);

                    }
                }
     }
}

```

::update::

Looking at the code you edited into the question this should just about get you there. (can't test it obviously so use with caution)

```
//make sure you call this before you start generating cunks!
//you will only need it once.
public void SetSeed(long seed)
{
    PerlinNoise.genGrad(seed);
}

//and since doing all the work related to setting the seed needs to be done only once, we can remove them from the function
public void GenerateChunk(float offsetX, float amplitude)
{
    for(float x = 0; x < CHUNK_SIZE; x += 1)
    {
            for(int subX = 0; subX < 16; subX += 1)
            {
                try
                {
                    //since we want "1d" noise, we always pass 0 as the y coordinate.
                    //we also don't pass the "multiplied by 16" x coordinate into the noise generator because that would distort the outcome.
                    float height = (float) PerlinNoise.noise(x+offsetX, 0);
                    height *= amplitude;

                    //400 seems to be offset height, you might still want to move that to the function call as a parameter.
                    //notice that i'm multiplying the x offset by 16 here rather than before possing it to the noise generator.
                    Block B = new Block(Material.DIRT, offsetX+(x*16), height + 400, new Image("res/Dirt.png"));
                    Blocks.add(B);
                    B.setVisible(true);
                }
                catch (SlickException e)
                {
                    e.printStackTrace();
                }
            }
     }
 }

```

---
Tags: java, 2d, perlin-noise
---


# Question
Title: Integrating SQLite to Cocos2d-x at Xcode
I have downloaded SQLite C/C++ interface to work with Cocos2d-x. Created a database by Firefox SQLite plugin. Then tried the following code

```
    // sqlite implementation
    sqlite3 *db;

    if(sqlite3_open("testdb.sqlite",&db) == SQLITE_OK){
        NSLog(@"Opened db Successfully");
    } else {
        NSLog(@"Failed to open");
    }

```

Output is # Failed to open

How to solve the issue?

# Answer
Well, you should start by checking the error code returned by sqlite3\_open. Different codes are there for a reason to suggest what the error might be.

I for one guess that the file was not found. Very often the current directory is not what you expect, and is oftent different on different platforms.
> 1 votes

# Answer
I have written a blog on how to integrate sqlite in your cocos2d-x game in xcode step by step. You can visit http://sqlite-integration-in-cocos2d-x.blogspot.in/
> 0 votes

---
Tags: c++, cocos2d-x, sql
---


title: What are Unity3D Substances?

text:
# Question
Title: What are Unity3D Substances?
I recently was a tutorial use **substances** in Unity3D. I understood that a *Substance* is a material we can dynamically manipulate at run time, but I am still unclear about it. Could someone shed some light on this?

# Answer
Substances are basically **dynamically generated materials**.

There main purpose is to take the **grunt work out of generating tileable materials** like bricks and stone roads and the like. Basically artist wont have to spend time dealing with things like aligning seams and what not.

They also have the advantage of drastically **reducing** the amount of textures **stored on the disk**.

They also are **resolution independent** meaning that you can create the texture at runtime to be as detailed as you need depending on resolution.

This does not however come for free the texture will still have to be store in memory and **will cost you** as far as RAM consumption.

So you will have some input textures that will be used to dynamically generate your substance.

Wether you should use them or not depends on totally what your trying to achieve. They are particularly useful if you want to say have multiple looks applied to the same object at different times in your game.

The tech that unity uses is from this company http://www.allegorithmic.com/ and if you want to truly take advantage of this you will probably need to buy a substance editor from them as they make it pretty easy to build different materials.

They have some cool tools just be aware of the performance implications.

So a practical example of use would be:

Say I wanted to make a game where the same environment would look aged when the character came back to it years later.

You would build your substance so that the sliders will expose some cracks on the table and perhaps even some peeling of the finish. All changeable during runtime. With some exposed parameters also changeable in the editor.

Example of that is here ---\> https://www.youtube.com/watch?v=AxAw7LIqIKM
> 5 votes

# Answer
They are dynamically generated textures. http://www.allegorithmic.com

Substances are created with substance designer using stock images, vector graphics, code functions, or other substances to generate a new texture. Substances are VERY convenient and and nice. They really shine when you want to add variety to textures while keeping disk size low (as long as the substance is built correctly).

You can also have unity generate a new substance variant at runtime for individual game objects. Although, the you would need to check if the substance is finished generating the texture as each substance has a runtime as well before applying it, otherwise the object will appear solid blue until it is finished.
> 1 votes

---
Tags: unity, substance-engine
---


# Question
Title: How do I handle collision response between many different types of game objects?
I am looking for a way to avoid the dreaded switch or if/else scenarios between numerous game object types when a collision takes place in a game. For example:

You have a list of game objects which inherit from a common class such as GameObject. You check the list for any collisions and call a method for each colliding object to respond to the collision, but this situation develops:

```
public void handleCollision(GameObject other) {
    switch(other.getType()) {
    case Alien:
    //Perform some logic
    break;

    case Ogre:
    //Perform some logic
    break;

    case Wall:
    //Perform some logic
    break;

    case Door:
    //Perform some logic
    break;

    //and so on

    }
}

```

This would become unwieldy with hundreds of different game object types. What I was attempting to do was this:

```
Map<CollisionKey, Method> collisionCallbackMap = new HashMap<CollisionKey, Method>();

collisionCallbackMap.put(new CollisionKey(gameObjectType, gameObjectType), //add a reference to a method here);

```

CollisionKey is a class I created for handling game object pairs such as Player-Alien, Player-Ogre, Player-Wall, etc. The idea was to look up a pair of game objects in the map, cast the game object in the collision list to the appropriate class types, and pass them into the method stored in the value slot of the map for that game object pairing. So it would look something like this:

```
for(GameObject a : collisionListA) {
    for(GameObject b : collisionListB) {
        if(a.collidesWith(b)) {
            collisionCallbackMap.get(new CollisionKey(a.getType(), b.getType(), //cast GameObjects to appropriate types such as Player and Alien and pass it into a method here);
        }
    }
}

```

The method called from the map would look something like this if the game objects colliding were a Player and an Alien:

```
public void playerToAlienCollision(Player p, Alien a) {
    //Perform some logic here such as...

    p.reduceHealth();
    a.reduceHealth();

    a.knockBack();
}

```

This wouldn't be a problem if I were working in, say, C++ with function pointers, but I'm working in Java with Android. Android's Java only supports Java 6, and if I'm not mistaken I believe it now has support for Java 7, but it does not currently support the recently released Java 8. With the addition of lambdas and method references in Java 8 I feel this would be a viable approach, but I don't have access to that so I need another solution. The workaround or Java's version of function pointers before Java 8 seems to involve interfaces with a single method and I believe I would need one for each collision method. It just looks convoluted and not very polished. The accepted answer of this question displays an example of it:

https://stackoverflow.com/questions/4480334/how-to-call-a-method-stored-in-a-hashmap-java

I'm not looking for how collision detection is done, I'm ok with that, its what comes right after I'm seeking a solution for. What is an efficient way to handle collision response and callbacks without the dreaded and bloated switch or if/else scenarios? I think of a large game like Runescape with tons of objects and its written in Java and wonder how they set up their collision response/callbacks.

# Answer
> 2 votes
Use interfaces (available in Java 6).

If all objects collide under the same loop, then you can have them all implement the same functions but perform different logic.

```
ICollidable{
  bool CollidesWith(ICollidable other);
  void handleCollision(ICollidable other);
  void reactToCollision(ICollidable other);
}

GameObject implements Icollidable {
  ...
  void handleCollision(ICollidable other){
    this.reactToCollision(other);  // calls reduceHealth();
    other.reactToCollision(this);  // calls knockback();
  }
  ...
}

```

The gist of this is that java doesn't need function pointers. It has something better.

---

Aside 1: if you attempt to write functions like this:

```
public void playerToAlienCollision(Player p, Alien a)

```

You haven't solved the "dreaded switch or if/else scenarios", you've only relocated it. You still have to write `n^2` functions to accomplish collisions, where before you had to write `n^2` switch cases. If each object is responsible for its own behavior during a collision, you only have to write `n` implementations of the interface. Also, you avoid global function declarations that need tight coupling to both classes.

---

Aside 2: if you detect collisions like this:

```
for(GameObject a : collisionListA) {
  for(GameObject b : collisionListB) {
    if(a.collidesWith(b)) {
      ...

```

Then you have not yet mastered the art of detecting collisions, either. But thank you for explicitly excluding that topic from your question.

---
Tags: java, android, collision-detection, collision-resolution, callbacks
---


# Question
Title: Merging several textures into one using RGB channels
Would it be possible to place a texture into each RGB channel?

Example: Red = wood.png Blue = tiles.png Green = metal.png

The advantages I could see are saving space, memory and draw calls and the resolution might not suffer. (unless I'm missing something)

I've seen people pack many textures into one but they have to be scaled to fit which lowers resolution.

# Answer
> 0 votes
Not realistically, no.

When you pack an image into a color channel, you make one of two trade-offs:

1) The first case is when you only need a single color channel (greyscale image). This is not true is the usual case. Your wood.png likely has a mix of RGB colors (giving it the brown tint). Note that you can actually ignore color in your images in some cases by converting your images to gradient maps. However, this works along with normal maps, meaning you still need 3 channels for your image. This is commonly done for bitmap fonts and some other types of images, but not diffuse color images like you specified.

2) The second case is when you can ignore most of the texture hardware (mipmapping/filtering) and hence can use a 16-bit image and then pack your RGB data into a single channel at reduced color accuracy. The filtering hardware doesn't know how to deal with this which is why you can't use filtering if you do this. It's often done for some kinds of data-buffers (like g-buffers in deferred shading situations) but filtering is not needed in those cases.

You could use a **texture array** for them (assuming they are all the same dimensions and format), which would reduce your draw calls but not bandwidth or memory.

---
Tags: textures, shaders
---


title: Where is the Aves game engine?

text:
# Question
Title: Where is the Aves game engine?
The Aves game engine made a splash last spring/summer, with very impressive demo videos. I went back to check on them, and it looks like their site has long since died. Google also doesn't seem to know anything new about them.

Where can I find news about Aves? Is the project dead?

# Answer
> 7 votes
Dextrose was acquired by Zynga ( creators of Farmville, mafia wars )

http://www.insidesocialgames.com/2010/09/24/zynga-acquires-dextrose-aves-engine-html5/

# Answer
> 2 votes
While momboco's answer is indeed the case the tech talks and other presentations on the engine have a lot of useful information about game development using HTML5 and ***not*** using canvas. I have used a few of these tricks in my latest project and built a scrolling map world rendering through HTML and CSS including an isometric view with a good deal of success.

# Answer
> 2 votes
Paul Bakaus shared some info in a 26 Oct 2012 comment on this Google Talk video.

> As creator of the engine, let me chime in. You are partially right in that we have never released the full blown iso engine, but we did in fact release individual components of it at https://github.com/zynga.
>
> Most notably our state-of-the-art build system Jasy (https://github.com/zynga/jasy), our JavaScript foundation Core (https://github.com/zynga/core), and a couple of highly performance optimized frontend components such as Scroller (https://github.com/zynga/scroller) or Viewporter (https://github.com/zynga/viewporter).
>
> I know you'd really like to see more isometric game-centric code, and hey, never say never. We need more people like you pushing for it to make it happen.

In a conversation with Jason Mayes on Google+ he also states "Some of the content is outdated now though, Canvas is definitely a viable tech to build games now :)"

---
Tags: javascript, html5
---


# Question
Title: How simulate the return effect of the wheel of fortune needle
I am trying to create a spinning wheel which slows down after a specific time. I managed to simulate the slowdown of the wheel but I need also to put a needle which go up and down with an angle of 45°.

Here my wheel with the needle :

My wheel turn in clockwise and the needle (object in red in the above scheme) rotate in counter clockwise.

Once done the needle back to his original position slower than the previous movement.

The code i wrote :

```
// Once 3 seconds are passed, the speed rotation start to decrease
If RealMillisecs() -_fRotateTime > 3000 Then
    If _fSpeedRotation > 0 Then
        _fSpeedRotation = _fSpeedRotation - 0.001
    Else
        _fSpeedRotation = 0
    EndIf
EndIf

_fWheelRotation -= _fSpeedRotation * dt.frametime

// If the needle is not going back to its orginal position then is going up
If not _bAnimBackNeedle Then
    _fNeedleRotation = _fWheelRotation Mod 45 * -1

   /* If its previous rotation greater than actual position
    it's mean that the needle has reach its max angle (45)*/
    If _fNeedleRotation < _fPreviousNeedleRotation Then
        _bAnimBackNeedle = True // The going back animation to true
    EndIf

    _fPreviousNeedleRotation = _fNeedleRotation
EndIf

// If the going back animation is set to true or the wheel has stopped to turn
// get the needle back to its position at constant speed
If _bAnimBackNeedle Or _fSpeedRotation = 0 Then
    _fNeedleRotation -= 0.5 * dt.frametime
    If _fNeedleRotation <= 0 Then
        _bAnimBackNeedle = False
    EndIf
EndIf

```

My code doesn't make what i hope.

The needle doesn't come back to its original position when the wheel is stopped.

How can I managed the code to have the wheel and the needle with a good behaviour?

# Answer
> 12 votes
How about letting box2d do the work for you? It wasn't too difficult for me to setup everything in RUBE:

There are two major parts: the wheel and the needle.

## Wheel

1. First there is a base. In this case the base is a static body with a square fixture.
2. The wheel is attached to the base via a revolute joint. This joint allows the wheel to spin freely about the center.
3. The wheel consists of 33 circle fixtures: 1 big wheel and 32 pegs. I created the pegs using a simple Rubescript. The pegs and wheel are on different bitplanes, allowing the needle to collide only with the pegs and not the wheel. One other ajustment is that the boolean `isBullet` needs to be true; the reason for this is that the pegs can move very quickly when the wheel is spinning fast and sometimes the peg-needle collision will be missed by box2d. If the `isBullet` flag is set, box2d resolves those cases correctly.

## Needle

1. The needle is a body with a single fixture in the shape of a kite. I have increased the friction a little on the needle fixture and peg fixtures. This way when the needle rubs against the pegs it will eventually slow the wheel down. We also need to set the bitplane and bitmask of the needle so it only collides with the pegs.
2. The needle can rotate about the revolute joint. The second body for the revolute joint is the static body from before.
3. Two opposing distance joints act as springs to try and keep the needle in place. The damping parameter on the distance joints also helps dissipate the wheel's energy.

## Result

You get a lot of nice realisms when you go with a physics-based solution. Most notably, you can let the player actually spin the wheel with a swipe of their finger or a click+drag of their mouse. Also, it's easy to do things like add more needles for more players if you want to.

I know there is a lot of stuff here specific to box2d which you might not be familiar with but it is well worth learning IMO. The spinning wheel is an excellent way for you to get started.

# Answer
> 0 votes
As a side-note, your use of EndIf makes me think you're trying to do this in PHP - which makes no sense whatsoever, but whatever. It would help if you could clarify what language you're working with.

But concerning the mathematics alone...

The two events you need to catch are when the edge of the space contacts the needle and when the edge breaks contact with the needle.

```
if( (fWheelRotation + 7) % 45 < 6 )
{
    fNeedleRotation = ((((367 - fWheelRotation) % 45)^2) * 1.8);
} else {
    if( fNeedleRotation < 0 )
    {
        fNeedleRotation = 0;
    }
    else if( fNeedleRotation < 46 )
    {
        fNeedleRotation -= 10;  // Adjust this value to control return speed
                                // Be sure to allow a small overshoot
    }
}

```

Due to how close to the threshold you're operating, the offset offers a buffer. Without the buffer, a fast-spinning wheel could bypass the (much smaller) trigger zone(s) without the needle responding.

I could offer a slightly more elegant solution if you included what language you're using.

---
Tags: mathematics, algorithm
---


title: PyGame2Exe doesn't include spritesheet?

text:
# Question
Title: PyGame2Exe doesn't include spritesheet?
My directory for my Pygame program looks something like this:

```
[Parent directory]
    lib
        engine
            Various .py files
        graphics
            spritesheet.py
            spritesheet.png
    skeleton.py (starter script)
    font.ttf
    spritesheet.png
    pygame2exe.py (Pygame2Exe script)

```

When I run pygame2exe.py (found here, everything seems fine: the dist directory is created with an executable file and all the necessary dlls. However, when I try to run the program, it says I cannot find the file "lib\graphics\spritesheet.png"

I've tried to manually insert the image file by using 7zip to "open" the .exe; however 7zip doesn't support it. That seemed to be the best solution, but now I am stumped. Does anyone have an answer?

# Answer
> 1 votes
In `pygame2exe.py`, there's a section which reads:

```
#Extra files to be included in the dist directory
                  #directory #files
extra_files = [ #("",        ["README.txt"]),
              ]

```

You should add your content (`spritesheet.png`, `font.ttf`) into this array and run pygame2exe again.

---
Tags: python, pygame
---


# Question
Title: How can I fix this error about loading .wav assets in MonoGame 3.2?
I'm trying to add a music file to my project, but I get the error "Could not load EpicScores.wav asset!"

I load the music file like this:

```
Song sound1 = Content.Load<Song>(@"EpicScoreCreatorOfWorlds.wav");

```

I've tried both with and without the `.wav` ending.

My file is added to the *Content* folder, and I've made sure my file properties are set to the "Content" build action and to "copy always."

Why do I get this error and how can I fix it?

# Answer
Per this thread on the MonoGame forums, this appears to the result of a legacy MonoGame feature that allowed the loading of unprocessed `.wav` files via the content pipeline API without *actually* using the content pipeline.

You should leverage the content pipeline to load your assets (the content pipeline will transform your assets from their source format to a more suitable runtime format; that's why you don't need the file extension in the load call, because you're actually loading a different kind of file than you'd think).

This involves creating a content project for your content, adding the music asset and setting the content processor for it (as you've previously set the build actions; you probably want `MonoGame Song` in this case).
> 2 votes

# Answer
http://jaquadro.com/2013/11/migrating-monogame-projects-to-vs2013-and-windows-8-1/

I found out how I can get Content Pipeline to work for Visual Studio 2013, in the above link.
> 1 votes

# Answer
If i am correct you cannot load .wav files as 'song'. wav files may only be used as 'Sound Effects' .you can convert the file to .wma and then use it.U also have to create .xnb file. For a song to play on windows 8/windows phone ,u have to copy both the wma file and xnb file to the content folder.

Here is a solution that i created by modifying 'Xnacontentcompiler' which is an opensource project.

http://1drv.ms/1drPvzv

run xnacontentcompiler(assuming you have xna4.0). use the format converter to convert file to wma and then create xnb file for that wma. now copy both the xnb and wma to your content folder,change property to content and copy always and load the file like you normally do.
> 0 votes

---
Tags: monogame
---


# Question
Title: try to create CCSpriteFrame but get nil values
I'm trying to animate a CCSprite in cocos2d v3 following this question, but I'm getting the following error message in Log:

```
    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM
 insertObject:atIndex:]: object cannot be nil'

```

This is my code:

```
NSMutableArray *animationFrames = [NSMutableArray array];
    int frameCount = 0;
    for(int i = 1; i <= 9; ++i)
    {
        CCSpriteFrame *spriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [NSString stringWithFormat:@"hero-%d.png", i]];

            [animationFrames addObject:spriteFrame]; //ERROR OCCUR THIS LINE

        frameCount++;
        if (frameCount == 8) break;
    }

```

The problem is that all spriteFrames are nil, but I don't why. I already tested the i values with NSLog, and also tried to add hero-1.png to a CCSprite object and works fine. I also tried to add all fixed hero-1.png in all frames to verify if the problem was with i variable. But didn't work also.

# Answer
This work! in cocos2d 3.x

NSMutableArray \*frames = \[NSMutableArray array\];

```
int frameCount = 0;

    for (int i = 1; i <= 5; i++) {
        CCSpriteFrame *frame = [CCSpriteFrame frameWithImageNamed:[NSString stringWithFormat:@"dice0%d.png",i]];

        [frames addObject:frame];
    }

CCSprite *sprite = [CCSprite spriteWithSpriteFrame:frames.firstObject];
[self addChild:sprite]; // or to whatever object it will be parented to
sprite.position = ccp(WIDTH*0.5, HEIGHT*0.5);

CCAnimation *animation = [CCAnimation animationWithSpriteFrames:frames delay:0.5];
CCAction *animateAction = [CCActionAnimate actionWithAnimation:animation];
[sprite runAction:animateAction];

```
> 1 votes

---
Tags: software-engineering, cocos2d-iphone, objective-c
---


# Question
Title: How can I simulate a floating character in Box2D?
I am creating a jump'n'run game using the Box2D physics engine. The main character should be a robot like creature without legs, floating over the ground powered by a jet engine.

The motion should look like that of a flying saucer: The creature never touches the ground, but also never gets too far from it. What construction of joints, shapes and bodies can do that nicely?

I started by trying to make a kind of pendulum:

```
     O        <-- head
     |
    +-+
    |X|       <-- creature's body
    +-+
 ----+-----   <-- ground (pendulum crossing)
     |
     O        <-- heavy body, weld joined to the creature, it does
                  collides with nothing, just pulling the creature
                  down to keep it upright

```

However, that isn't working smoothly and the creature bounces around too much. Besides, how can I simulate the jet engine nicely?

# Answer
**UPDATE**: over the years I've become a bit more knowledgeable, and I realized Setup 2 can be modeled in a simpler way. I've added Setup 3, which I believe is the best solution.

Your question inspired me to play around with the RUBE editor to find a nice solution. Here's what I came up with:

## Setup 1

Let's start with the simpler one on the left. It has the following setup (from the bottom up):

1. A wheel body that can roll back and forth
2. A small box (chassis) attached to the wheel via a `b2RevoluteJoint`. The chassis body is not allowed to rotate.
3. A main UFO body (no rotation)
4. A `b2PrismaticJoint` connecting the centers chassis and UFO body (this makes sure the UFO is always upright)
5. A `b2DistanceJoint` connecting the centers of the chassis and the UFO body. This allows the UFO to bob up and down and eventually settle on a set distance from the chassis (how fast this happens depends on the frequency and damping ratio).

The result:

The idea would be to only render the ufo part, and use collision filtering so the rest of the physics in your game (with the exception of the ground) does not interact with the wheel part. In the gif you can see that the wheel doesn't climb over other bodies (as it shouldn't), so if you want to include steps in your game then you need to add hidden ramps and/or change the shape of the physics ground so that the wheel can climb up the steps.

## Setup 2

If you want more than just vertical motion, then I recommend the second setup:

This case is the same as the first, with the following ammendments:

1. `b2Distance` and `b2PrismaticJoint`s from before are now connected to a small, intermediate body which still has rotation disallowed.
2. The new intermediate body is connected via `b2RevoluteJoint` to the main UFO body. The UFO body is now allowed to rotate.
3. In order to constrain the UFO body from freewheeling, we need to stabilize it. Fortunately the method for doing so was already determined in this answer. The four distance joints are attached to the main UFO body and the new intermediate body. However, when playing around with the UFO in RUBE, I noticed that the parallel distance joint configuration as suggested in that answer was unstable, and it kept 'snapping' into the cross configuration seen in the above image. Since that was much more stable, I decided to go with it.

The result:

## Setup 3

Setup 2 is a little bit complicated, and a slightly better setup can be achieved with fewer bodies and joints:

1. Wheel, same as before.
2. This time around, the wheel is connected to body 3 using a `b2WheelJoint`. This negates the need for the chassis body from the first two setups. The `PrismaticJoint` is also no longer needed, as its behavior is built in to the `b2WheelJoint`.
3. A small intermediate body is still needed to connect the wheel to the main body. This body has the fixed rotation flag set for two reasons: it keeps the UFO upright (by fixing the vertical axis between the wheel and itself) and it provides the constant reference angle for the main body.
4. The small body at position 3 is connected to the main body through a `b2WeldJoint`. The `b2WeldJoint` is primarily used to 'glue to bodies together', but here the constraint can be made soft by selecting the frequency and damping in a similar manner to the `b2DistanceJoint`.
5. The main UFO body.

This setup has done away with 3 joints and 1 body compared to Setup 2. All of the joint anchors are now placed in logical locations on the model, as opposed to those floating `b2DistanceJoint` anchor positions in Setup 2, which should be much simpler to construct and debug in actual game code. Finally, Setup 3 also has the bonus of not over shooting when the wheel runs into a barrier; notice how in the Setup 2 the UFO body overshoots the wheel position an snaps back when the wheel runs into an obstacle at high speed? The bottom `b2RevoluteJoint` is separating under the load. This doesn't happen to the `b2WheelJoint` in Setup 3.

Whatever you end up doing, I highly recommend trying it out in RUBE, its a great way to try and find fun feeling physics solutions.
> 16 votes

# Answer
NauticalMile's answer is great (and bonus points for the killer animated diagrams). To give an alternate suggestion that doesn't suffer from the same problems (the wheel collision stopping you from moving past objects that a floating body should be able to traverse effortlessly, I suggest modelling something more closely matched to the reality of your situation. I.e. don't use rigid body collision and springs.

Model your character as a rigid box as normal, but every update do a raycast directly downwards (in the direction of your jet thrust) and measure the distance from the character to the nearest collidable object. Then, apply an upward impulse to your character's body, inversely proportional to the distance from the ground. So the closer you are to the ground, the larger the impulse. That can be a linear proportion, or an exponential proportion, but you don't want it to be too large (i.e. shooting off into the sky) so you'll want to damp it beyond a certain range. But basically it should achieve equilibrium against the effects of gravity, to give the effect of a spring - the closer you get to the ground, the more energy the spring imparts, the further away the less it boosts you. Combined with a damping factor on the motion, you should achieve a balance point some height off the 'ground'.

NB: this force should be constrained to only act vertically on your body, otherwise you start getting into real-world issues where your character is unstable and wants to lurch forwards or backwards depending on what's underneath or what angle the character is at.

Jumping is then simply adding an extra vertical factor to that force - you can't jump infinitely high, but it does have the extra nuance that if you time the jump right (say just after dropping down from a height), you can get extra height on the jump by taking advantage of the bounce effect.

This should have the effect of allowing smooth motion over small obstacles without taking anything away from your horizontal velocity. As the obstacle comes under the jet raycast, the character will shift upwards, but not slow down at all.

Actually, a single raycast may be unstable, especially if you're moving over rough terrain. I'd perhaps do two or three raycasts and take an average of the distance; weighting it if you want to maybe, or discarding measurements outwith a certain deviation from the average. What you're don't want a case where the character moves over a very slim gap in an otherwise flat surface in the world and drops downward sharply because the ray happened to pierce right into that gap.
> 3 votes

---
Tags: box2d, simulations, character, motion
---


# Question
Title: Is there a way to use other fonts, besides the default ones in OpenGLUT?
I'm using OpenGLUT functions like glutBitmapString to render sentences and words in a game. However, there is a limited set of fonts to use and I need some bigger size fonts. Is there a way to add new fonts to these functions/API?

Thanks

# Answer
Try Freetype OpenGL, a library for displaying a unicode text using a (single) vertex buffer and freetype fonts. Have a look at their **web**, **repository** and **documentation**.

An example, from their website:

```
    /* Text to be printed */
    wchar_t *text = L"A Quick Brown Fox Jumps Over The Lazy Dog 0123456789";

    /* Texture atlas to store individual glyphs */
    texture_atlas_t *atlas = texture_atlas_new( 512, 512, 1 );

    /* Build a new texture font from its description and size */
    texture_font_t *font = texture_font_new( atlas, "./Vera.ttf", 16 );

   /* Build a new vertex buffer (position, texture & color) */
    vertex_buffer_t *buffer= vertex_buffer_new( "v3i:t2f:c4f" );

    /* Cache some glyphs to speed things up */
    texture_font_load_glyphs( font, L" !\"#$%&'()*+,-./0123456789:;<=>?"
                                     L"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
                                     L"`abcdefghijklmnopqrstuvwxyz{|}~"

    /* Where to start printing on screen */
    vec2 pen = {0,0};
    vec4 black = {0,0,0,1};

   /* Add text tothe buffer (see demo-font.c for the add_text code) */
    add_text( buffer, font, "Hello World !", text, &black, &pen );

```
> 2 votes

---
Tags: opengl, c++, fonts, glut
---


title: Concurrent touches not being detected

text:
# Question
Title: Concurrent touches not being detected
I have pretty much the same controls on the race example of the engine. A `AnalogOnScreenControl` and a button defined by a `Sprite`.

The problem is, when I'm using the analog directional, touching the button does not trigger `onAreaTouched` on the button sprite.

I even tried adding the button to the child scene (controller scene) but it doesn't register the secondary touch on the button.

Am I doing something wrong or is this a bug?

**UPDATE**

I am doing some debugging and apparently if I touch the control base, it triggers it's `onAreaTouched`, and if I keep touching the controls and then touch the button (on the other side of the screen) the same `onAreaTouched` from the control base is triggered. He's the only one receiving the touch event.

I really can't understand why this is happening.

# Answer
Found out the stupid engine option missing. When creating the `EngineOptions` you have to add this:

```
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);

engineOptions.getTouchOptions().setNeedsMultiTouch(true);

if(MultiTouch.isSupported(this)) {
    if(MultiTouch.isSupportedDistinct(this)) {
        Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
    }
} else {
    Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
}

```
> 1 votes

---
Tags: java, andengine, touch
---


title: Java Animating using drawImage

text:
# Question
Title: Java Animating using drawImage
Hi I have a tile based game and I would like to know how to animate the grass image this is what I have so far:

```
public class dirt extends block{

    float frame = 0;
    public dirt(int x,int y){
        this.x = x;
        this.y = y;
        r = new Rectangle(x - (int)tilemap.camx,y - (int)tilemap.camy,20,20);
        solid = false;

    }

    public void tick(){
        createCollisionRect();

        int tester = (int)(frame +.1);

        if(tester < 3){
            frame+=.1;
        }else{
            frame = 0;
        }

    }

    public void render(Graphics g){
        ImageIcon i62 = new ImageIcon("res/grasssheet.png");
        img = i62.getImage();
        g.drawImage(img, x - (int)tilemap.camx,y-(int)tilemap.camy,x+20,y+60/***/,0,20*(int)frame,60,20*(int)frame + 20,null);
        //g.drawImage(img, x- (int)tilemap.camx,y-(int)tilemap.camy, null);

    }
}

```

This kinda works but I don't why all the images glitch out.

I think I need an image observer but I don't understand that so if that's the problem explain what I have to please.

# Answer
It looks like you are drawing directly to the graphics objects instead of buffering. Have you seen the documentation?

Java has a `BufferStrategy` class that might help you. You should do your drawing off-screen, then switch the view using the `BufferStrategy` object, removing all flickering.

You might want to look at some Java game engines though: They already do a lot of the heavy lifting for you, letting you focus on the game logic and play.
> 1 votes

# Answer
Your question is too vague.
What do you mean by "glitch out"?

From the look of the drawImage I assume that you want to draw a single 'frame' (20px\*20px) from the spritesheet? That's not what I see there.
Try:

```
g.drawImage(img.getSubimage((frame*20),0,20,20), x - (int)tilemap.camx, y-(int)tilemap.camy, null);

```

Also, you shouldn't be reloading the images on every render call. Load it once and, for example, pass it in the constructor, or, better yet, create a tile 'Type', load the image once there and give each tile a reference to a tile type.
(And is there a reason you are loading it as an ImageIcon as opposed to, say, a BufferedImage?)
> 0 votes

---
Tags: java
---


# Question
Title: OpenGL 3.3: render to framebuffer w/o depth attachment
I want to render my scene to a framebuffer and store the RGBA values in a texture. For this, I attach a texture to GL\_COLOR\_ATTACHMENT0. When I define a GL\_DEPTH\_ATTACHMENT texture as well, everything is rendered with the correct depth. However, if I leave out the depth attachment (because I don't need it in a later stage), wrong depth values are output, if I further use the RGBA texture (e.g. when blitting the framebuffer to another one).

Is this correct behavior, i.e. do I always need to specify a depth attachment?

**edit:** *wrong depth values:* By attaching a GL\_COLOR\_ATTACHMENT0, a color texture (e.g. RGBA) is output. Without a depth attachment, the colors are at the wrong "depth", in the sense that the pixels of an object behind a wall are rendered, although the corresponding pixels of the wall should be rendered instead.

Regards, bobbel

# Answer
You need to attach *something* to `GL_DEPTH_ATTACHMENT` if you want to render with depth testing and writing, but it doesn't have to be a texture. If you don't need to read the contents of the depth buffer in a shader (e.g. for shadow mapping), you can use a Renderbuffer object instead. Using a Renderbuffer object for the depth buffer may offer a performance benefit over using a texture.
> 4 votes

---
Tags: opengl, frame-buffer
---


# Question
Title: Determining whether an object is in field of view considering obstacles
I'm thinking of stealth games where an object has a certain field of view that you want to avoid otherwise game over.

The field of view may be linear or circular or any arbitrary group of pixels/tiles.

If I don't consider obstacles (for example, if you're standing behind a wall, they can still see you), I can determine whether the player is within an object's field of view using simple geometric properties using the two object's positions and range. This can be done efficiently, though it kind of assumes the objects are points.

However, to make it realistic, you should be able to hide behind a wall or a tree without being seen.

How is this problem usually solved?
What are some articles that I can read to understand more about this problem?

# Answer
Basically, you're going to be doing raycasting to figure out where exactly the vision gets blocked. The complexities come in with trying to make that clean and efficient and fit with how you're managing the actual scene. Other people have done a much better job explaining everything than I can, so I'm just going to reference them.

Amit has a fantastic overview here, and there's another great one here. For the second, there's also some relevant discussion here. Note that these are for 2D games, but the concepts are still the same for 3D.
> 4 votes

---
Tags: line-of-sight, visibility-determination
---


title: What are Blackboards?

text:
# Question
Title: What are Blackboards?
I am implementing an Entity System for my game. I am aiming for a larger procedurally generated world. The world will be filled by AI entities where "on screen" and "near screen" entities will be updated regularly, while the "far away" entities will only be updated sometimes.

My initial thought was to implement a message queue... which is filled during a loop and invoked after the loop, but before the next loop. Then I read this, in there there is an answer mentioning Blackboards(the one with 12 votes), but I haven't been able to find anything detailed on Blackboards.

The question is what *exactly* are they and what would I gain by using them when compared to message queue ?

My language of choice is CSharp.

# Answer
> 4 votes
Blackboard systems started in AI programming. Their context in Entity systems is less of a problem solving role, and more of a "place to exchange information" role.

The implementation of the blackboard system can very a lot. Even to the point that you wouldn't be able to tell the difference between that and a message que. It's just a known place to put information that all the entities have access to.

I wouldn't worry too much about the exact definition. Many things game development are just loose guidelines, not rules. And actually the main thing you should be getting from that other thread is to focus on the simple solution. There's no need for a complex system, when a simple one will do just fine.

---
Tags: c#, entity-system, messaging
---


# Question
Title: How to create more vertexes from within a shader in OpenGL?
when rendering voxels in octrees, the only information necessary is the current octree-level, -position and colour/texture. But one has to send eight vertices to the rendering pipeline in order to render a complete cube and still needs colour/texture.

Is there a better way?

Since geometry-shaders wont be wide-spread for quite some time the "emit\_vertex"-method in the geometry-pass wont suffice (or am i wrong? i don't think mesa currently supports geometry-shaders). Also, afaik, backface-culling is done before the geometry-pass, so that would lead to additional overhead.

My current idea is to send 'dummy vertices' and have the actual drawing data in between but that really shouldn't be the solution.

kind regards

# Answer
Geometry instancing is a good way to solve this. Since all the models you're rendering are identical (cubes), you can provide an "inner" vertex buffer containing the 8 vertices for a single cube, plus an "outer" vertex buffer with just one vertex per cube, containing all the per-cube information. The two buffers will get "multiplied" together during rendering - that is, the vertex shader will run once for each vertex of each cube, and the per-cube information will be replicated to all 8 vertices in that cube.

A similar trick is often used for drawing particle quads, using instancing to provide the 4 vertices per particle, so that the "outer" vertex buffer can have just one vertex per particle.

You can google for more information on how to actually implement geometry instancing in OpenGL, but here is one tutorial.
> 0 votes

---
Tags: opengl, shaders, voxels, octree
---


# Question
Title: The correct way to transform a ray with a matrix?
Playing with XNA Triangle Picking Sample I found out that it does not work well if you scale the world matrix of the objects you want to pick. When I dug into the implementation I found this comment in the `RayIntersectsModel` method:

```
        // The input ray is in world space, but our model data is stored in object
        // space. We would normally have to transform all the model data by the
        // modelTransform matrix, moving it into world space before we test it
        // against the ray. That transform can be slow if there are a lot of
        // triangles in the model, however, so instead we do the opposite.
        // Transforming our ray by the inverse modelTransform moves it into object
        // space, where we can test it directly against our model data. Since there
        // is only one ray but typically many triangles, doing things this way
        // around can be much faster.

```

After the comment they actually transformed the ray:

```
ray.Position = Vector3.Transform(ray.Position, inverseTransform);
ray.Direction = Vector3.TransformNormal(ray.Direction, inverseTransform);

```

With this implementation, picking suffered from "short-sightedness" if you scaled the models: it could only pick those objects, that were close enough to it. Even the ray-boundingSphere intersection test, which implementation is hardcoded into XNA, failed in the same way.

I fixed this by "doing the wrong thing" - I actually started transforming every vertex by the model's world matrix and to fix the boundingSphere test I added this code:

```
Quaternion rot;
Vector3 scale, trans;
modelTransform.Decompose(out scale, out rot, out trans);

float maxScale = Math.Max(Math.Max(scale.X, scale.Y), scale.Z);

boundingSphere.Center = Vector3.Transform(boundingSphere.Center, modelTransform);
boundingSphere.Radius *= maxScale;

```

This obviously is not optimal and I wanted to know if there is a way to actually transform the ray back to the model's space with the model's inverted matrix, while making it work for scaled matrices?

**SOLUTION: Thanks to Nathan's answer I found a way to fix the ray scaling - just renormalize the ray direction:**

```
ray.Position = Vector3.Transform(ray.Position, inverseTransform);
ray.Direction = Vector3.TransformNormal(ray.Direction, inverseTransform);
//ADD THE FOLLOWING LINE:
ray.Direction.Normalize();

```

**SOLUTION UPDATE: As I tested the app, I found that Nathan was indeed completely right and another change was necessary. Here is the full code for the correct RayIntersectsModel() method:**

```
static float? RayIntersectsModel(Ray ray, Model model, Matrix modelTransform,
                                out bool insideBoundingSphere,
                                out Vector3 vertex1, out Vector3 vertex2,
                                out Vector3 vertex3)
{
    vertex1 = vertex2 = vertex3 = Vector3.Zero;
...
    Matrix inverseTransform = Matrix.Invert(modelTransform);
    // STORE WORLDSPACE RAY.
    Ray oldRay = ray;

    ray.Position = Vector3.Transform(ray.Position, inverseTransform);
    ray.Direction = Vector3.TransformNormal(ray.Direction, inverseTransform);
    ray.Direction.Normalize();

    // Look up our custom collision data from the Tag property of the model.
    Dictionary<string, object> tagData = (Dictionary<string, object>)model.Tag;

    if (tagData == null)
    {
        throw new InvalidOperationException(
            "Model.Tag is not set correctly. Make sure your model " +
            "was built using the custom TrianglePickingProcessor.");
    }

    // Start off with a fast bounding sphere test.
    BoundingSphere boundingSphere = (BoundingSphere)tagData["BoundingSphere"];

    if (boundingSphere.Intersects(ray) == null)
    {
        // If the ray does not intersect the bounding sphere, we cannot
        // possibly have picked this model, so there is no need to even
        // bother looking at the individual triangle data.
        insideBoundingSphere = false;

        return null;
    }
    else
    {
        // The bounding sphere test passed, so we need to do a full
        // triangle picking test.
        insideBoundingSphere = true;

        // Keep track of the closest triangle we found so far,
        // so we can always return the closest one.
        float? closestIntersection = null;

        // Loop over the vertex data, 3 at a time (3 vertices = 1 triangle).
        Vector3[] vertices = (Vector3[])tagData["Vertices"];

        for (int i = 0; i < vertices.Length; i += 3)
        {
            // Perform a ray to triangle intersection test.
            float? intersection;

            RayIntersectsTriangle(ref ray,
                                    ref vertices[i],
                                    ref vertices[i + 1],
                                    ref vertices[i + 2],
                                    out intersection);

            // Does the ray intersect this triangle?
            if (intersection != null)
            {
                // RECOMPUTE DISTANCE IN WORLD SPACE:
                Vector3 vertexA = Vector3.Transform(vertices[i], modelTransform);
                Vector3 vertexB = Vector3.Transform(vertices[i+1], modelTransform);
                Vector3 vertexC = Vector3.Transform(vertices[i+2], modelTransform);

                RayIntersectsTriangle(ref oldRay,
                                    ref vertexA,
                                    ref vertexB,
                                    ref vertexC,
                                    out intersection);

                // If so, is it closer than any other previous triangle?
                if ((closestIntersection == null) ||
                    (intersection < closestIntersection))
                {
                    // Store the distance to this triangle.
                    closestIntersection = intersection;

                    // Store the three vertex positions in world space.
                    vertex1 = vertexA;
                    vertex2 = vertexB;
                    vertex3 = vertexC;
                }
            }
        }

        return closestIntersection;
    }
}

```

# Answer
Transforming the ray position and direction by the inverse model transformation is correct. However, many ray-intersection routines assume that the ray direction is a unit vector. If the model transformation involves scaling, the ray direction won't be a unit vector afterward, and should likely be renormalized.

However, the distance along the ray returned by the intersection routines will then be measured in model space, and won't represent the distance in world space. If it's a uniform scale, you can simply multiply the returned distance by the scale factor to convert it back to world-space distance. For non-uniform scaling it's trickier; probably the best way is to transform the intersection point back to world space and then re-measure the distance from the ray origin there.
> 9 votes

---
Tags: mathematics, matrix, raycasting
---


# Question
Title: How to match user click and the sprite object position in libGDX framework
I am using libGDX Java framework for developing a practice game in Eclipse.

My game is in landscape mode and I am using sprite image for game assets. Actually I am trying to follow the Kilobolt Zombie Bird tutorial.

I have set orthographic camera like this:

```
cam = new OrthographicCamera();
cam.setToOrtho(true, 250, 120);

```

I have done this because my background texture region is of 250 x 120 px in the sprite image.

So basically my sprite image is small in size and it is getting scaled according to the device but all the computing is done relative to 250 x 140 px like for changing the position of the object I have defined `Vector2 position = new Vector2(x, y);` and if I write `position.x = 260;` the sprite will go outside the screen even if my device width is 500px.

**Problem:**

Now I have to make the moving sprite vanish when someone clicks on it (just imagine zombies moving around and if I click on them they die). So I am using the following code for matching user click coords with the object coords:

```
int x1 = Gdx.input.getX();
int y1 = Gdx.input.getY();
if(position.x == x1 && position.y == y1){
    // do something that vanish the object clicked
}

```

The problem is `position.x` and `position.y` returns the coords relative to the ortho cam width and height which is 250 x 120 px and the click coords are relative to the device width and height which maybe anything according to the device. Because of this even if I click right on the object the click coords and the object position coords have a huge difference in their values. So I would never get matching values.

Is there any solution for this or am I doing it wrong?

# Answer
> 5 votes
Before using the coordinates of your touch event, you need to scale them to your camera dimentions. You can try this code :

```
OrthographicCamera cam;
Sprite sprite;    // your sprite
Vector3 touchPos; // creates a vector3 object for our touch event

 touchPos = new Vector3();
 cam = new OrthographicCamera();
 cam.setToOrtho(true, 250, 120);

public void render(float delta) { // you need to put it into the main loop
        if (Gdx.input.isTouched()) {
         touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); //when the screen is touched, the coordinates are inserted into the vector
         cam.unproject(touchPos); // calibrates the input to your camera's dimentions
                 if (touchPos.x > sprite.getX() && touchPos.x < sprite.getX() + sprite.getWidth()) {
                          if (touchPos.y > sprite.getY() && touchPos.getY() < sprite.getY() + sprite.getHeight()) {
                                //clicked on sprite
                               // do something that vanish the object clicked
              }
             }

```

---
Tags: java, libgdx, coordinates
---


# Question
Title: unity rts on mobile : how can units find each other as simple as possible
**Situation**:

* I have a grid of 100 by 100 tiles.
* each tile has a list of units that are currently standing ontop of it.
* in this grid 500 units of team 1 and 500 units of team 2 are randomly walking around.
* while they are walking around they place themselves in the unitlist of each tile they are on.

**problem**: Each unit has to check lets say a square of 6 by 6 tiles around the tile he is on, to check if there is an enemy nearby.

**my solution**. each unit checks on top of what tile he is and only when it changes tiles it will check the 36 tiles around its current tile and check all their unitlist to check for nearby enemies...

**Question**.

1. isn't there a better way to do this? Because when I need my units to have a bigger line of sight of lets say 15tiles it needs to check 1000units * 15tiles \*15tiles = a gazillion...
2. Does there exist a very inexpensive way of using somekind of a basic circle collider in unity without the need for rigid bodies etc...?

# Answer
Yes, Unity contains physics OverlapSphere function. This requires the objects have colliders, but does not require rigid bodies. The performance of this is hard to judge until you actually use it in your implementation.

If you run into performance issues, I would suggest however you implement some kind of quad/octree as suggested in this related question. Additionally, there are a number of algorithms defined for nearest neighbor searches, you should read through them and see what fits the requirements of your project.
> 1 votes

---
Tags: unity, rts
---


# Question
Title: Movement and rotation of bodies in top down game
We are developing a 2D top down game with libgdx using the included box2d as physics engine.

We don't want our bodies to accelerate but to instantly move with the wanted velocity. The bodies are moved like this, which works perfectly for our purpose:

```
Vector2 currentVelocity = body.getLinearVelocity();
Vector2 targetVelocity = velocity.velocityApplyVector.cpy();
targetVelocity.sub(currentVelocity);

targetVelocity.scl(body.getMass());

body.applyLinearImpulse(targetVelocity, body.getWorldCenter(), true);

```

The problem now is, that we also want the bodies to instantly rotate to the direction they are facing. The direction of the player is determined by the mouse position, so it is possible that the body is moving in another direction than it is facing. I tried to accomplish it like this:

```
float bodyAngle = body.getAngle() * MathUtils.radDeg;
float totalRotation = (inputRotation - bodyAngle) % 360;
if(Math.abs(totalRotation) > 1) {
    if ( totalRotation < -180) totalRotation += 360;
    if ( totalRotation >  180) totalRotation -= 360;
    float impulse = body.getInertia() * totalRotation;
    body.applyTorque(impulse, true);
}

```

This causes the body to rotate in the wanted direction but it needs multiple frames until it totally reaches the wanted angle.

The body mass is set to 70 and the angular damping to 8 (I tried some values for the damping and 8 was the best value for my cause, but that's, of course, not a final solution...).

I guess I have to somehow increase the needed impulse depending on the body mass and the angular damping (we want to be able to change it) but I can't figure out how to get the values right. I don't want to use `setTransform` since it totally destroys the physically correct behaviour of the bodies. How can I calculate the needed values? Is there any better way to solve my problem?

# Answer
> 5 votes
## Simple Solution

If you want the body to instantly rotate just call `Body::setTransform` and pass the current position and the desired angle, don't bother applying torques or anything.

The function call could be something like this:

```
body.setTransform(body.getPosition(),myDesiredAngle);

```

## Physics Solution

If you want the player body to interact with bodies while rotating to the cursor position (i.e. you can knock them out of the way) then I would recommend another method:

The numbers in the figure above are described here:

1. The player body. An isoceles triangle shows the direction the body is pointing
2. A kinematic body. This is not necessary for your game, it just plays the roll of continuously moving the player to the right while allowing it to face another direction. It is connected to the player body via a revolute joint
3. A cursor body. This body should not collide with anything. This body will follow the cursor as closely as possible (more on that later)
4. A wheel joint connecting the player body to the cursor body. We really want it to act as a slider (prismatic joint), but we also don't need to constrain the angle of the cursor body. This joint will force the player body to face the cursor body at all times. As such we want the frequency, damping ratio, motor speed, and max motor speed all set to zero.

The result:

Now you will notice that in the rube editor it's just the mouse (mouse joint) that I used to move the cursor body around, and I didn't achieve the instantaneous rotation you are looking for. But do not dispair, because you can get around this in one of two ways:

1. Set the transform of the cursor body at every step like described in the simple solution above. I'm not sure that this won't break physics all the time. If the player body is locked in a corner it might just move through other bodies to satisfy the joint constraint.
2. Create a second cursor body. Connect the second cursor body to the first using a motor joint (box2d 2.3.0). I used a max force of 10N and a correction factor of 0.90. In the game, the transform of the second cursor body is then set to the position of the cursor every time step.

In the gif below, the second cursor body is the larger square body:

As a side note, the motor joint was surprisingly stable. I tried to get it to work with a distance joint and kept getting jitters and/or cases where the high damping caused a slow contraction of the joint.

My intuition tells me there will still be kinks for you to work out. The problems you encounter will depend on your gameplay.

---
Tags: libgdx, box2d, rotation, physics
---


title: OpenGL - Disable Anti Alias

text:
# Question
Title: OpenGL - Disable Anti Alias
I can't find anything on how to hint to the driver to disable any antialias. I'm using a very minimal passthrough setup yet I notice my driver is still doing what looks like MSAA. I want to disable this, or at least give a strong hint to disable it, so to save performance. As I will be doing deferred rendering with my own SSAA.

# Answer
OpenGL drivers allow user to force enable AA. I'd like to see a workaround of that too, but I'm afraid there's none.

Possible solution would be to render to a texture through FBO (which is not controlled by drivers AA setting?) and then render that texture pixely-perfect to screen.
> 1 votes

---
Tags: opengl, antialiasing
---


title: Handle movement with QuadTree

text:
# Question
Title: Handle movement with QuadTree
I currently have a `QuadTree` that contains all my Entities. It works well and I've optimized it pretty decently, but the one thing that hurts is that I am removing from and inserting to it almost every frame. A little code:

```
    entityMap.remove(it->second, it->second->getLastAABB()); // Removes the entity, getLastAABB is it's last location

    QuadTree* nearest = entityMap.getLowestRoot(moved);
    std::unordered_set<Locatable*> entities = nearest->getAll();
    for (auto itt = entities.begin(); itt != entities.end(); itt++) {
        AABB aabb = (*itt)->getAABB();
        if (aabb.collides(moved)) {
            // COLLISION
        }
    }

    entityMap.insert(it->second);

```

That code gets run 30 times a second. I use a dirty flag so that only entities that have moved are dealed with. `entityMap` is the `QuadTree` itself.

Any advice to decrease `insert` and `remove` calls is appreciated.

# Answer
> 2 votes
Contrary to the common belief you can optimize the quad tree function insert. The common implementation of insert, is to traverse from root to the leafs and find the most fit node, in Game programming gems 2 there is an article that details how you can instantly find that node, if you know the extents of the quatree(can be extended to octree) and the extents of the object bounding box. This way you can instantly determine the level and the node that contains the box. Fortunately you find full explanation in this article.

You can also track the neighbors of each node, hence, when an object moves you know where it's going, this work especially when you have a complete quatree, otherwise I suggest the first approach.

# Answer
> 1 votes
I'm guessing that `insert` and `remove` traverse the quad tree from root to leaf, and that's why you are concerned about its performance?

(By the way, rule of thumb is never perform any optimisations unless you've asked "have I measured a real performance problem" and can answer in the affirmative.)

In games, the vast majority of movement would be continuous, that is, your entities will be moving from one leaf node to a neighbour. You would have a tree with linked leaves, so even if the leaves share a very distant ancestor, you only need to follow the local links instead of all the way up the tree.

---
Tags: c++, movement, optimization, tree
---


title: Texture coordinates for a 3D box

text:
# Question
Title: Texture coordinates for a 3D box
I have a box model in my DirectX application, stored as 8 vertices:

```
MyVertex vertices[] =
{
    { DirectX::XMFLOAT3(  - 1.0f,  + 1.0f,  - 1.0f ), /*,tex coord...*/}, //0
    { DirectX::XMFLOAT3(  + 1.0f,  + 1.0f,  - 1.0f ), /*,tex coord...*/}, //1
    { DirectX::XMFLOAT3(  + 1.0f,  + 1.0f,  + 1.0f ), /*,tex coord...*/}, //2
    { DirectX::XMFLOAT3(  - 1.0f,  + 1.0f,  + 1.0f ), /*,tex coord...*/}, //3

    { DirectX::XMFLOAT3(  - 1.0f,  - 1.0f,  - 1.0f ), /*,tex coord...*/}, //4
    { DirectX::XMFLOAT3(  + 1.0f,  - 1.0f,  - 1.0f ), /*,tex coord...*/}, //5
    { DirectX::XMFLOAT3(  + 1.0f,  - 1.0f,  + 1.0f ), /*,tex coord...*/}, //6
    { DirectX::XMFLOAT3(  - 1.0f,  - 1.0f,  + 1.0f ), /*,tex coord...*/}, //7
};

```

And for the index buffer I use:

```
WORD indices[] = {
    3,1,0,2,1,3, //top
    0,5,4,1,5,0,
    3,4,7,0,4,3,
    1,6,5,2,6,1,
    2,7,6,3,7,2,
    6,4,5,7,4,6,
};

```

It works just fine, but now I want to add a texture to the faces of my box.

## **Which would be the best approach?**

The options I see:

1. Use 24 instead of 8 vertices -- four for each of the box's six faces. Some of these will have the same position/normals, but different texture coordinates.
2. Use 8 vertices and texture coordinates like here:
3. **MAYBE** there is a way to provide different sets of texture coordinates for a single vertex, so I can provide different texture coordinates on different faces of the box? If so, how can I do that?

The **disadvantages** (for the options with the same numbers):

1. 16 additional vertices (3 as many), all the benefits of using a index buffer to have less vertices are wasted - maybe this means I shouldn't use an index buffer at all, under this approach?
2. Texture with odd proportion (2:3), texture must be six times the size for the same resolution.
3. None?

In option 2. I can use one texture to create different images on each box's face, but I'm not interested in that benefit.

## **Additional question (!!!):**

**How is this done in 3d software and mesh formats?**

When I create a box in 3ds Max, create a material with a texture and apply it to the box, each side of box has the same texture (like option #1), with good texture coordinates (impossible to achieve with 8 vertices and a single square texture?), and the statistics says "8 VERTEXES".

**How is it possible?** Did they achieve option #3?

# Answer
> 2 votes
A vertex is not just a spatial *position*, but a whole bag of *attributes*.

* A *position* `p` is a point in some spatial space or a homogeneous coordinate.
* A *texcoord* `tc` is a point in texture space.
* A *normal* `n` is a bivector, and so on.

If you represented a vertex with multiple indices, a vertex `V_k` could be represented by a tuple of indices `{p_a, tc_b, n_c}`. In a single-indexed environment like Direct3D or OpenGL, you can only have one index. This means that your index values will be `{p_i, tc_i, n_i}`, or in short, `i`.

If you've got multi-indexed geometry like in the former case, the way you can make it single-indexed is to for each unique tuple of indices, generate a new set of vertex attribute data with the same single-indexed index. If you've seen the tuple before, reuse the index; otherwise generate a new vertex.

If you have ever loaded the Wavefront OBJ file format, this will be painfully familiar to you as OBJ stores separate streams for each attribute and uses multi-indexed tuples like outlined above.

Other file formats use other approaches like pre-baked deduplicated single-indexed attribute streams, or completely non-indexed attribute streams, which is equivalent to deduplication without actual deduplication, just repeating the data for each vertex in each face.

# Answer
> 2 votes
I'd use a cube map. That way you can still only 8 vertices. You'll have to rework your texture that your sampling from and your texture coordinates will be three values instead of two.

---
Tags: c++, textures, directx, coordinates, 3dsmax
---


title: How to trust a UDP Client

text:
# Question
Title: How to trust a UDP Client
I'm working on a Unity project with the Lidgren UDP library for connection. I'm new to networking, so I'm not sure on general "best practices" for this area. I'm trying to figure out a good way to be able to quickly trust and verify a received UDP message.

I currently keep a dictionary of players with each player assigned an UID (uint) from the server when the player connects. This UID serves as the key in the dictionary. The player is told their UID. Nothing secret being communicated here, like usernames/passwords, so I'm not worried about things like that.

So I'm having a problem with wrapping my head around how to trust the messages. Things like position updates and user actions will be sent from client-\>server via UDP. I was thinking of a quick way to process these messages is by including the UID at the start of each message, checking the UID, grabbing the corresponding player from the dictionary, and then updating the players position that way.

But I'm worried that can be easily spoofed/manipulated. All it'd take is some mischief maker to figure it out, and then start inserting random position updates (for themselves or others).

Is there an efficient, more fool proof way to ensure the message is from who it claims to be? Do I have to just rely on comparing IPEndPoints to tell? Is there anything specifically to Lidgren I can or should use?

Please don't respond if all you have is "don't worry about it" or "why would anyone want to do this?" I'd rather learn proper processes now than down the road when/if it becomes a problem.

# Answer
> 3 votes
always double check on the server, don't allow teleportation through position but instead ensure the speed isn't too large

you can ensure authenticity by having the client keep a counter and encrypt it together with UID with a prearranged client-specific secret (also send the unencrypted counter to account for lost packets)

# Answer
> 2 votes
Remember that Lidgren sends messages that are assigned 'MessageTypes'. One of those MessageTypes is a StatusChanged (Connecting, Connected, Disconnected, etc)

Lidgren assigns each new connection with a unique remote identifier. If you couple that with packet encryption that is available via the Lidgren framework then that should be sufficient.

Client connects to the server, server verifies the connection and assigns that client a unique remote identifier (this is handled by Lidgren, and the identifier can be accessed on any incoming message that is read with server.ReadMessage() by accessing it as follows:

```
NetIncomingMessage msg = server.ReadMessage();
string uniqueID = NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier); // as shown in the examples provided by Lidgren.

```

Once the client has made a connection to your server, you may send a 'sharedkey' from the server to the client (you may wish to encrypt this message with a key that every client shares locally, just so it's not transmitted in 'plaintext')

Once the client knows the sharedkey, you can then begin encrypting your messages from the client/server and decrypting them at either end using that sharedkey.

# Answer
> 0 votes
Calling `Network.InitializeSecurity()` prior to initializing the server is supposed to prevent this sort of attack.

---
Tags: unity, networking, udp
---


# Question
Title: What is Vector Projection and what is it's use in games?
Couldn't find a clear enough answer on Google.

I know what vectors are. But what does it mean to project a vector onto another, and what is it used for in games?

# Answer
> 6 votes
Vector projection means finding the components of vector **a** that are in the same direction of vector **b**. Check my answer here for how to do it.

Not only vector projection is important in game dev but vector decomposition in general, where you have a vector and you need to decompose it into 3(or 2) separate vectors in the u,v,w directions.

For example in order to find a local frame of reference (read: object space/coordinates) you often need to find three linearly independent vectors which form the frame of reference. You can start by finding the projection on **X** axis (or the local **u** direction) and then continue with cross product to find the third vector. The final step would to cross product the result two vectors from the previous operations.

Another situation in physics simulation you will often have force vectors that you need to find their sum in each direction, you cannot do that unless you do vector decomposition.

---
Tags: mathematics, vector
---


# Question
Title: Stopping sprites from toppling off platform
I am new to Unity and am trying to create a simple 2d platformer. I have applied a box collider to my player sprite and the floor/platform its standing on. Now when I go over the platform, it toppes off of it as expected, but I want it to simple fall off it instead of toppling. How can I do this?

Also I saw a video of Unity Live Training in which he was using a separate circular collider for the player's feet. When I did this, the sprite started rolling.

Can anybody help me with this?

# Answer
> 0 votes
There is an "fixed angle" option on Rigidbody2D component,enabling that works

---
Tags: 2d, unity, sprites, platformer
---


# Question
Title: How do I lerp between values that loop (such as hue or rotation)?
**View Demo**

I'm trying to make the joint rotate smoothly around the center of the canvas, toward the angle of mouse pointer. What I have works, but I want it to animate the shortest distance possible to get to the mouse angle. The problem occurs when the value loops around at the horizontal line (`3.14` and `-3.14`). Mouseover that area to see how the direction switches and it takes the long way back around.

**Relevant Code**

```
// ease the current angle to the target angle
joint.angle += ( joint.targetAngle - joint.angle ) * 0.1;

// get angle from joint to mouse
var dx = e.clientX - joint.x,
    dy = e.clientY - joint.y;
joint.targetAngle = Math.atan2( dy, dx );

```

How can I make it rotate the shortest distance, even "across the gap"?

# Answer
It’s not always the best method, and it can be more computationally expensive (though this ultimately depends on how you store your data), but I will make the argument that lerping 2D values works reasonably well in the majority of cases. Instead of lerping a desired angle, you can lerp the desired normalised direction vector.

One advantage of this method over the “pick the shortest route to angle” method is that it works when you need to interpolate between more than two values.

When lerping hue values, you can replace `hue` with a `[cos(hue), sin(hue)]` vector.

In your case, lerping the normalised joint direction:

```
// get normalised direction from joint to mouse
var dx = e.clientX - joint.x,
    dy = e.clientY - joint.y;
var len = Math.sqrt(dx * dx + dy * dy);
dx /= len ? len : 1.0; dy /= len ? len : 1.0;
// get current direction
var dirx = cos(joint.angle),
    diry = sin(joint.angle);
// ease the current direction to the target direction
dirx += (dx - dirx) * 0.1;
diry += (dy - diry) * 0.1;

joint.angle = Math.atan2(diry, dirx);

```

The code can be shorter if you can use a 2D vector class. For instance:

```
// get normalised direction from joint to mouse
var desired_dir = normalize(vec2(e.clientX, e.clientY) - joint);
// get current direction
var current_dir = vec2(cos(joint.angle), sin(joint.angle));
// ease the current direction to the target direction
current_dir += (desired_dir - current_dir) * 0.1;

joint.angle = Math.atan2(current_dir.y, current_dir.x);

```
> 14 votes

# Answer
The trick is to remember that angles (at least in Euclidean space) are periodic by 2\*pi. If the difference between the current angle and the target angle is too large (i.e. the cursor has crossed the boundary), just adjust the current angle by adding or subtracting 2\*pi accordingly.

In this case, you can try the following: (I've never programmed in Javascript before, so forgive my coding style.)

```
  var dtheta = joint.targetAngle - joint.angle;
  if (dtheta > Math.PI) joint.angle += 2*Math.PI;
  else if (dtheta < -Math.PI) joint.angle -= 2*Math.PI;
  joint.angle += ( joint.targetAngle - joint.angle ) * joint.easing;

```

---

**EDIT**: In this implementation, moving the cursor too quickly around the center of the joint causes it to jerk. This is the intended behavior, since the angular velocity of the joint is always proportional to `dtheta`. If this behavior is undesired, the problem can easily be fixed by placing a cap on the angular acceleration of the joint.

To do this, we'll need to keep track of the joint's velocity and impose a maximum acceleration:

```
  joint = {
    // snip
    velocity: 0,
    maxAccel: 0.01
  },

```

Then, for our convenience, we'll introduce a clipping function:

```
function clip(x, min, max) {
  return x < min ? min : x > max ? max : x
}

```

Now, our movement code looks like this. First, we calculate `dtheta` as before, adjusting `joint.angle` as necessary:

```
  var dtheta = joint.targetAngle - joint.angle;
  if (dtheta > Math.PI) joint.angle += 2*Math.PI;
  else if (dtheta < -Math.PI) joint.angle -= 2*Math.PI;

```

Then, instead of moving the joint immediately, we compute a target velocity and use `clip` to force it within our acceptable range.

```
  var targetVel = ( joint.targetAngle - joint.angle ) * joint.easing;
  joint.velocity = clip(targetVel,
                        joint.velocity - joint.maxAccel,
                        joint.velocity + joint.maxAccel);
  joint.angle += joint.velocity;

```

This produces smooth motion, even when switching directions, while performing calculations in only one dimension. Furthermore, it allows the velocity and acceleration of the joint to be adjusted independently. See demo here: http://codepen.io/anon/pen/HGnDF/
> 12 votes

# Answer
I love the other answers given. Very technical!

If you want, I have a very simple method to accomplish this. We'll assume angles for these examples. The concept can be extrapolated to other value types, such as colors.

```
double MAX_ANGLE = 360.0;
double startAngle = 300.0;
double endAngle = 15.0;
double distanceForward = 0.0;  // Clockwise
double distanceBackward = 0.0; // Counter-Clockwise

// Calculate both distances, forward and backward:
distanceForward = endAngle - startAngle;    // -285.00
distanceBackward = startAngle - endAngle;   // +285.00

// Which direction is shortest?
// Forward? (normalized to 75)
if (NormalizeAngle(distanceForward) < NormalizeAngle(distanceBackward)) {
    // Adjust for 360/0 degree wrap
    if (endAngle < startAngle) endAngle += MAX_ANGLE; // Will be above 360
}

// Backward? (normalized to 285)
else {
    // Adjust for 360/0 degree wrap
    if (endAngle > startAngle) endAngle -= MAX_ANGLE; // Will be below 0
}

// Now, Lerp between startAngle and endAngle.

// EndAngle can be above 360 if wrapping clockwise past 0, or
// EndAngle can be below 0 if wrapping counter-clockwise before 0.
// Normalize each returned Lerp value to bring angle in range of 0 to 360 if required.  Most engines will automatically do this for you.

double NormalizeAngle(double angle) {
    while (angle < 0)
        angle += MAX_ANGLE;
    while (angle >= MAX_ANGLE)
        angle -= MAX_ANGLE;
    return angle;
}

```

I just created this in the browser and has never been tested. I hope I got the logic right the first try.

**\[Edit\] 2017/06/02 - Clarified the logic a bit.**

Start by calculating distanceForward and distanceBackwards, and allow the results to extend beyond the range (0-360).

Normalizing angles brings those values back into the range of (0-360). To do this, you add 360 until the value is above zero, and subtract 360 while the value is above 360. The resulting start / end angles will be the equivalent (-285 is the same as 75).

You next find the smallest Normalized angle of either distanceForward or distanceBackward. distanceForward in the example becomes 75, which is smaller than the normalized value of distanceBackward (300).

If distanceForward is the smallest AND endAngle \< startAngle, extend endAngle beyond 360 by adding 360. (it becomes 375 in the example).

If distanceBackward is the smallest AND endAngle \> startAngle, extend endAngle to below 0 by subtracting 360.

You would now lerp from startAngle (300) to the new endAngle (375). The engine should automatically adjust values above 360 by subtracting 360 for you. Otherwise you would have to lerp from 300 to 360, THEN lerp from 0 to 15 if the engine doesn't normalize the values for you.
> 3 votes

---
Tags: mathematics, javascript, animation, lerp, easing
---


title: Creating teams 2v2, 3v3, etc

text:
# Question
Title: Creating teams 2v2, 3v3, etc
I'm figuring out how to create games with teams. The problem is that there will be games 1v1, 2v2, and so on as well as free for all. What would be the most efficient way to do this in Unity C#?

I'm thinking of making a Dictionary with players' instances and every player has an index for a team. For example, we have 2v2 game, two players have teamIndex 1 and the other two have teamIndex 2. Is this the right way to do it, or there is a better way?

Thank you!

# Answer
> 0 votes
You'll have a list of all players in the game. That list will contain player structures that contain whatever data about each player you may need, including their team. Yes, using a index for team is just fine. Or you can use a name, or reference a team object that contains more information about the team.

A single list is fine. You don't need to do anything extravagant like dictionaries or multiple lists. This is a list that's not going to be more than 10 or 20 items. Iterating through the list to find teams or certain information is trivial.

If you want to get more complicated for easier access, create an additional list of Team objects. Each team will have a unique identifier (like the index you have, or a name or color). Then, each team will also contain a list of references to the players that are part of that team.

You can use something like `Dictionary<int, List<Player>>` where each player list is indexed by the team index. Or a `List<Team>` where each `Team` object has a `List<Player>` inside of its structure.

There are lots of ways to do this. With such a small list, don't worry about performance. Just make it easy to use for the things you want to use it for. You don't have to separate the free-for-all and team modes. In free-for-all, just give each player their own team.

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


# Question
Title: Unity3D How to tell when editor script is added to object
What I want is a way that an editor script can tell when it has been attached to an object in the scene.

OnEnable() and Awake() only happen when you bring an object with the editor script attached to it up in the inspector.

Is there any built in method to accomplish this? Or perhaps some work around? The editor script only needs to tell when itself has been added to an object, not any other components.

# Answer
If you add the attribute \[ExecuteInEditMode\] to the script, just before the script class name, it will be run in editor mode. These tagged scripts will have their `Start()` function called (and I believe the `OnEnable()` and `Awake()`, though I haven't tested it), and a few others given some conditions:

* `Update` is only called when something in the scene changed.
* `OnGUI` is called when the Game View recieves an Event.
* `OnRenderObject` and the other rendering callback functions are called on every repaint of the Scene View or Game View.

For example:

```
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class Example : MonoBehaviour {
    public Transform target;
    void Update() {
        if (target)
            transform.LookAt(target);

    }
}

```
> 1 votes

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


# Question
Title: How do I make an object's y-axis align with a Vector3?
I have a golf ball on the ground, and from a raycast, I have the normal which gives me the slope of the ground by the ball.

I have an object which is rendered on the HUD to show that slope to the player.

I have a parent object rotated -90 degrees around X, so that the indicator's Z-axis points up. This way I can do this:

```
Quaternion yRot = Quaternion.Euler(0, -CameraController.Instance.CachedTransform.eulerAngles.y, 0);
Vector3 displayGroundNormal = yRot * _groundNormal;
_lieIndicator3DParentCachedTransform.rotation = Quaternion.LookRotation(displayGroundNormal);

```

This, as far as I can tell, takes the ground normal, rotates it around the y-axis so that it shows the proper perspective given the camera's facing. Then it tells that parent object to look in that direction, which aligns its z-axis with the rotated ground normal.

This works, except the object I have also rotates around the y-axis depending on the orientation of the camera. I thought that I was throwing that information away in the second step by keeping only a Vector3 aligned with the ground normal rotated for the camera position.

So I want this:

Not this:

# Answer
> 1 votes
Construct the normal relative to the camera:

`Quaternion yRot = Quaternion.Euler(0, -CameraController.Instance.CachedTransform.eulerAngles.y, 0);
Vector3 displayGroundNormal = yRot * _groundNormal;`

Get the yz-plane projection of the adjusted ground normal:

`Vector3 yzNormalComponents = new Vector3(0, displayGroundNormal.y, displayGroundNormal.z);`

Get the angle between the yz-plane projection and the y-axis:

`float zAngle = Vector3.Angle(yzNormalComponents, Vector3.up) * Mathf.Sign(displayGroundNormal.z);`

Now rotate the z-axis toward the negative y-axis by that angle:

`Vector3 zDir = Vector3.RotateTowards(Vector3.forward, Vector3.down, zAngle * Mathf.Deg2Rad, 3);`

Use Quaternion.LookRotation to look in the calculated z direction, with the adjusted ground normal as up:

`_lieIndicator3DParentCachedTransform.rotation = Quaternion.LookRotation(zDir, displayGroundNormal);`

---
Tags: unity, quaternion
---


title: DirectX: Render the black bars

text:
# Question
Title: DirectX: Render the black bars
I'm still quite a beginner in the industry. I'm working on a game with some friends and I would like to add a cinematic between 2 levels like in the attached picture.

My question is how can I render the black bars in DirectX 9 or 11? Moreover, do I need to change the aspect ratio when I'm playing the cinematic?

# Answer
The black bars are nothing more than the cleared back buffer. The video is simply being centered and played between these two bars. This effect is known as Letterboxing. The only thing you need to do in DirectX is simply render the video accordingly (vertically aligned). That being said, a lot of the time these bars are shown because aspect ratio of the video is different than the game.

You do not change the resolution of the game while it's playing (at least, this is not a common approach). Rather, you calculate if the video aspect ratio matches the current aspect ratio, and if so, simply play it. If not, you can vertically center it.

\** Some games are known to use letter boxing regardless to indiciate a "scene". You may choose to do this, too.

This post by Nick Gravelyn has more info.
> 1 votes

---
Tags: c++, directx, directx11
---


title: WebSockets and Python/PyGame

text:
# Question
Title: WebSockets and Python/PyGame
I am looking to start development on a game that will have the server be written in Python/PyGame and the front end be in HTML5. What I would like to do is, with as minimal impact as possible, open up a WebSocket or two to allow the server to push events to my browser.

Is this possible with Socket.IO, or do I need an extra layer to handle WebSockets? I'd like to avoid importing and installing extra packages if possible.

# Answer
> 1 votes
Socket.IO is a protocol, not necessarily completely driven by WebSocket. In fact, Socket.IO even has a Flash fallback in place because of this. You can use just the Socket.IO library and simply communicate with the game accordingly if you're okay with this. Python libraries that implement the protocol do exist, such as this one. However, just keep in mind this is not **raw** web sockets.

Not that this might be an issue for you, of course it is your choice to evaluate. Socket.IO is supported in JavaScript so you can communicate between Python land and Socket.IO land with no additional libraries if you please.

---
Tags: python, pygame, websocket
---