title: Moving an object in a circular path

text:
# Question
Title: Moving an object in a circular path
I want to move one object (dot) in a circular path. How should I change the X and Y coordinates to accomplish this?

# Answer
> 70 votes
You can do that using simple math:

```
X := originX + cos(angle)*radius;
Y := originY + sin(angle)*radius;

```

*(originX, originY)* is the center of your circle. *radius* is its radius. That's it.

This works because the sine and cosine are mathematically related to the unit circle.

Image credit: LucasVB (Own work) \[Public domain\], via Wikimedia Commons. (Scaled down to 70%.)

# Answer
> 17 votes
You can use the parametric equation as marked by Krom. To understand why we used this formula you have to understand what the equation is. This equation is derived from the **Parametric equation of circle**.

Considering the circle is drawn with the center on the origin (O) as shown in the diagram below

If we take a point "p" on the circumference of the circle, having a radius r.

Let the angle made by OP (Origin to p) be θ. Let the distance of p from x-axis be y Let the distance of p from y-axis be x

Using the above assumptions we get the triangle as shown below :

Now we know that **cos θ = base/hypotenuse** and **sin θ = perpendicular/hypotenuse**

which gives us **cos θ = x/r** and **sin θ = y/r**

:: x=r\*cos θ and y=r\*sin θ

But if the circle is not at the origin and rather at (a,b) then we can say that the center of the circle is shifted

*a units in x axis*
*b units in y axis*
So for such a circle we can change the parametric equation accordingly by adding the shift on the x and y axis giving us the following equations :
**x=a+(r\*cos θ)
y=b+(r\*sin θ)**
Where a & b are the x,y co-ordinates of the center of the circle.

Hence we found x and y the co-ordinates of the point on the circumference of the circle with radius r

# Answer
> 7 votes
There's another trick, where you use the sin(x+a) and cos(x+a) formulas, and that allows you to compute sin(a) and cos(a) -- a being the angle by which you want to move from your current position -- only once and do simply multiplication and additions at each step.

sin(x+a) = sin(x)\*cos(a) + cos(x)\*sin(a), iirc.

Of course, that assumes constant angular velocity.

Beware of limited arithmetic precision, though. I've observed in the past "circular" motion implemented that way that would draw a spiral as a result of occasional rounding down repeated over time. It might be necessary to reset position to (x0, y0) after each revolution.

---
Tags: mathematics, graphics
---


# Question
Title: What factors affect the size of ammo limits?
In virtually all shooting games that use ammo, there is also a maximum ammo limit, which often varies between different ammo types. One obvious advantage of using ammo limits is to control the scarcity of ammo, so that players cannot excessively hoard it and drastically affect the game's difficulty.

What factors affect the size of ammo limits? An obvious factor would be the rate of consumption; if an ammo type is used by rapid fire weapons, the limit for this ammo type should be higher. But it should be obvious that there are many other factors, since some types of ammo quickly run out and others never seem to. As a designer, what factors should guide my decision for ammo limits, and when/why would I deliberately constrain or expand an ammo type's limit?

# Answer
The higher the damage output per second of a weapon, the more should you limit its ammo. Otherwise you give the player a too powerful tool to solve situations too quickly.

Let's say you have a huge boss monster. You invested plenty of time and resources into giving it lots of cool animations. To make sure that the player sees everything, you want the fight to take at least 60 seconds.

* You give the boss 1000 hit points.
* You give the player a pistol with 10 damage/s and a BFG with 100 damage/s.

When you give the player enough maximum ammo to use the BFG for a full 10 seconds, the fight will only last 10 seconds which would be too fast.

So you give the player enogh ammo to use the BFG for 4 seconds, which brings the boss down to 600 hit ponts. The player now needs an additional 60 seconds to kill it with their pistol, unless you allow them to scavenge for more BFG ammo during the fight.
> 2 votes

# Answer
This considerations Philipp brought up, while absolutely correct, already assume what kind of game you are talking about. As alluded to in the comment about Last of Us, different games are going for a very different feel, and ammo limits play into that. If the player feels very constrained by ammo limits, the game will feel more tense and claustrophobic. On the other hand, looser ammo limits make the player feel powerful and encourage more frantic gameplay.
> 0 votes

---
Tags: game-design, shooter, inventory
---


# Question
Title: NodeJS setTimeOut - How to run callback before delay time exceeded
I'm developing a card game server. I want to do this : While server process a turn for players, players have 20 seconds to do something. If players send a request to server within 20 secs, timer will stop and the callback will fire.

I'm doing like this :

self.tables\[table.id\].currentTimer = setTimeout(function () { callback(); }, 20\*1000);

How should I run the callback before delay time exceeded ?

# Answer
> 1 votes
Just stop the timer and then call the callback yourself.

```
clearTimeout(self.tables[table.id].currentTimer);
callback();

```

---
Tags: game-loop, node.js
---


# Question
Title: How can I change one prefab without changing all prefabs?
I have this code that will spawn in a lot of prefabs. It then edits the prefabs. The problem is that every time it changes a prefab it will reset and move all the other ones. Can you please explain this and maybe find a solution.

Here's the code:

```
void createAtom (int number, string symbol, string name, int x, int y) {
    Transform newatom = Instantiate (P_atom) as Transform;

    newatom.parent = this.transform;

    newatom.name = symbol;
    newatom.localScale = new Vector3 (0.35F, 0.35F, 1F);

    int posx = numbersx[x-1];
    int posy = numbersy[y-1];

    newatom.localPosition = new Vector3 ((posx * 2.1F) + (posx < 0 ? 1F : -1F), posy * 2.1F, -1F);//.GetChild (1);

    Debug.Log (number + symbol + name + x + y);
    TextMesh[] child = GetComponentsInChildren<TextMesh> ();
    child[0].text = symbol;
    child[1].text = number + "";
    child[2].text = "x0";
}

```

# Answer
```
TextMesh[] child = GetComponentsInChildren<TextMesh> ();

```

This line (and the three after it) is always getting the first three TextMeshes in the parent object's child hierarchy - not the hierarchy of the newatom you've just created.

That means that each time you create a new atom, you're overwriting the labels on the first atom you created, leaving the rest with their default values.

Instead, you probably want:

```
TextMesh[] child = newatom.GetComponentsInChildren<TextMesh> ();

```
> 1 votes

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


# Question
Title: Stat Multipliers: from Base Value or Iterative
I'm aware similar questions have been asked before but this time I'm asking about a **specific** issue with the maths of stat modifiers.

I have a stat system that applies a list of modifiers to a stat, modifiers can either **shift** of **scale** a stat. Shifting is easy, you either add or remove a set value, scaling involves multiplying that value by a factor.

What I'm struggling to work out is the best way to multiply. The simple method is to let each scaling modifier simply stack, e.g. if we have 2 modifiers: x1.5 and x2 to a stat of 1 we get:

**Stacked**

```
(1 * 1.5) * 2 = 3

```

The alternative is to have each modifier apply to the base number and then be added, soas with the previous example we get a situation where we workout how much the base is multiplied by and then remove the base to get the new addition:

**From Base**

```
1 + ((1 * 1.5) - 1) + (1 * 2) - 1) = 2.5

```

In this way each modifier acts on the base value so that you can *guaranty* a 50% increase in a stat won't cause a ridiculous increase and that a modifier isn't affected by the order that it's applied in. Mainly it's this ordering I'm worried about, this becomes evident when you add shifting, e.g. we have 3 modifiers: +1, x1.5 and x2, with the first method:

**Stacked**

```
((1 + 1) * 1.5) * 2 = 6

```

Where as with the second method:

**From Base**

```
(1 + 1)  + ((1 * 1.5) - 1) + ((1 * 2) - 1) = 3.5

```

It doesn't take too much to see that in the stacked method if the shift/addition were applied after the multipliers it would not result in the same value.

How do other games approach this problem? What is the best decision to make here?

# Answer
How many stat modifiers do you expect to be applied to these stats by the final part of the game? Is there a limit to how high these stats can go? Does the player gain these stat modifiers frequently or rarely? Do you want each new modifier to have a minor or major effect on the stats? Since we don't know anything else about your game, it seems that you should pick whichever approach satisfies your answers to these questions.

The **stacked** approach that you described makes each cumulative modifier have a dramatic effect on an already boosted stat. For example, having five ***x2*** modifiers would multiply a stat by 32. Add just one more ***x2*** modifier, and the stat is multiplied by 64! This might be alright if stat modifiers are very rare, or if there is some sort of limit to how many stat modifiers can be applied to the same stat. However, this will make unboosted stats look completely pathetic in comparison to any kind of boosted stat. Basically this method would make stats grow exponentially, like so:

On the other hand, the **from base** approach gives each individual modifier the same effect on the stat. In this case, having five ***x2*** modifiers would only result in the stat being multiplied by 5. Adding another one would increase the total multiplier to 6. This method would probably work better if you don't want multiple stat modifiers to have such a dramatic effect on stats. This method provides a more linear form of growth for stats, like so:

It would probably be easier to manage the **from base** approach in terms of balancing the game, but ultimately it is up to you to decide which approach fits your game better.
> 2 votes

---
Tags: game-design, software-engineering, game-mechanics
---


# Question
Title: How to increase the rotation of a quaternion by a percentage of X % in a Unity script?
There is a simple way to increase the rotation described by a quaternion by a percentage X?

Sorry, but in the documentation of Unity3D I found nothing and I have a poor knowledge on the topic.

# Answer
unless I'm mistaken you want 1+x/100 of a quaternion

```
quat*slerp(quaternion(), quat, X/100)

```

doing a slerp between the null quaternion and the target lets you get the power of a quaternion.

or you can acos the w component and then multiplying with the `fact = 1+x/100` factor and then get `quaternion(cos(acos_w*fact), sin(acos_w*fact)*normalized(quat.xyz))`

if you don't need massive accuracy then you can replace the slerp in the first solution with a lerp
> 1 votes

---
Tags: quaternion, unityscript
---


title: LibGDX Bounding Rectangles

text:
# Question
Title: LibGDX Bounding Rectangles
I'm creating some rectangles surrounding my sprites for my player and bullet class to detect collisions with the overlaps method in Intersector class of LibGDX.

I have a question:

When I instantiate Player and Bullet, I create a bounding box around the sprite using sprite.getBoundingRectangle() which returns a Rectangle object. I update the movement of these somewhere else in the main class.

When I update the movement of the bullet/player sprite, do I also need to update the position of the bounding box surrounding the bullet/player sprite? Or since the bounding Rectangle surrounds the sprite, will the box automatically move with the sprite?

Thanks

# Answer
> 1 votes
The bounding box automatically move with the sprite. If you don't believe it, use the ShapeRenderer to draw your sprite's bounding box each frame and check if it actually follow it or not.

---
Tags: java, collision-detection, libgdx, physics
---


# Question
Title: I am trying to implement a falling animation to my game and i am having alot of problems doing so
i am trying to have it so that when my character isnt touching anything he plays an animation of falling, yet when he moves from one game object to different one, he plays the animation. for example if he steps from one platform to another, even if he doesnt have to jump, he plays the falling animation. How would i make it so that when he jumps and doesnt touch anything he plays the animation?

```
  void Update()
{
    if(!colliding)
    {
        animator.Play ("Fall");
    }
  }
  void OnCollisionEnter(Collision collision)
{
    colliding = true;

}
void OnCollisionExit(Collision collision)
{
    colliding = false;
}

```

# Answer
> 1 votes
This can be done with a short timer. It is probably not a problem if the animation doesn't start immediately when the character starts falling.

```
public float delay = 0.1f; // Animation starts after 0.1 seconds of falling
private float lastCollision = 0.0f;
void Update()
{
    if(Time.timeSinceLevelLoad > lastCollision + delay)
    {
        animator.Play ("Fall");
    }
}

void OnCollisionStay(Collision collision)
{
    lastCollision = Time.timeSinceLevelLoad;
}

```

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


# Question
Title: How do you move a sprite in sub-pixel increments?
Pixels are either on or off. The minimum amount you can move a sprite is a single pixel. So how you make the sprite move slower than 1 pixel per frame?

The way I did it was to add the speed to a variable and test if it had reached 1 (or -1). If it did, then I would move the sprite and reset the variable to 0, like so:

```
update(dt):
    temp_dx += speed * dt
    temp_dy += speed * dt

    if (temp_dx > 1)
        move sprite
        reset temp_dx to 0
    if (tempy_dy > 1)
        move sprite
        reset temp_dy to 0

```

I disliked this approach because it feels silly and the sprite's movement looks very jerky. So in what way would you implement sub-pixel movement?

# Answer
There's a number of options:

1. Do as you do. You've already said it doesn't look smooth. There are some flaws with your current method though. For `x`, you could use the following:

```
tempx += speed * dt

while (tempx > 0.5)
  move sprite to x+1
  tempx -= 1
while (tempx < -0.5)
  move sprite to x-1
  tempx += 1

```

this should be better. I've switched the if statments to use 0.5, as when you're passed 0.5 you're closer to the next value than the previous. I've used while loops to allow for movement of more than 1 pixel per time step (it's not the best way to do it, but it makes for compact and readable code). For slow moving objects it'll still be jumpy though, as we haven't dealt with the fundamental issue of pixel alignment.
2. Have multiple graphics for your sprite and use a different one depending on the subpixel offset. To do subpixel smoothing only in x, for example, you could create a graphic for your sprite at `x+0.5`, and if the position is between `x+0.25` and `x+0.75`, use this sprite instead of your original. If you want finer positioning, just create more subpixel graphics. If you do this in `x` and `y` your number of renderings can quickly balloon, as the number scales with the square of the number of intervals: a spacing of `0.5` would require 4 renderings, `0.25` would require 16.
3. Supersample. This is a lazy (and potentially very expensive) way of creating a image with subpixel resolution. Essentally, double (or more) the resolution at which you render your scene, then scale it down at runtime. I would recommend care here, as performance can drop quickly. A less agressive way of doing this would just be to supersample your sprite, and downscale it at runtime.
4. As suggested by Zehelvion, it may be that the platform you are using already supports this. If you are allowed to specify non-integer x and y co-ordinates, there may be options to change the texture filtering. Nearest-neighbour is often the default, and this will cause "jerky" movement. Other filtering (linear/cubic) would result in a much smoother effect.

The choice between 2. 3. and 4. depends on quite how your graphics are implemented. A bitmap style of graphics suits pre-rendering much better, whereas a vector style may suit sprite supersampling. If your system supports it, 4. may well be the way to go.
> 17 votes

# Answer
One way in which many old-skool games solved (or hid) this problem was to animate the sprite.

That is, if your sprite was going to move less than one pixel per frame (or, especially, if the pixels/frame ratio was going to be something odd like 2 pixels in 3 frames), you could hide the jerkiness by making an *n* frame animation loop that, over those *n* frames, ended up moving the sprite by some *k* \< *n* pixels.

The point is that, as long as the sprite always moves in *some* way on each frame, there's never going to be any single frame where the whole sprite would suddenly "jerk" forward.

---

I couldn't find an actual sprite from an old video game to illustrate this (although I think e.g. some of the digging animations from *Lemmings* were like that), but it turns out that the "glider" pattern from Conway's Game of Life makes a very nice illustration:

Animation by Kieff / Wikimedia Commons, used under the CC-By-SA 3.0 license.

Here, the little blocks of black pixels crawling crawling down and right are the gliders. If you look carefully, you'll notice that they take four animation frames to crawl one pixel diagonally, but since they move in *some* way on each of those frames, the movement doesn't look that jerky (well, at least not any more jerky than anything looks at that frame rate, anyway).
> 14 votes

# Answer
The sprite's position should be kept as a floating point quantity, and rounded to an integer only just before display.

You can also maintain the sprite at super resolution and downsample the sprite before display. If you maintained the sprite at 3x display resolution,you'd have 9 different actual sprites depending on the subpixel position of the sprite.
> 6 votes

# Answer
The only real solution here is to use bilinear filtering. The idea is to let the GPU compute the value of each pixel based on the four sprite pixels that are overlapping with it. It's a common and effective technique. You simply need to place the sprite on a 2d-plain (a billboard) as a texture; then use the GPU to render these plains. This works well but expect to get somewhat blurry results and lose the 8-bit or 16-bit look if you were aiming for it.

pros:

Already implemented, very fast, hardware based solution.

cons:

Loss of 8-bit / 16-bit fidelity.
> 3 votes

# Answer
Floating point is the normal way of doing this, especially if you're eventually rendering to a GL target where the hardware is quite happy with a shaded polygon with float coordinates.

However there is another way of doing what you're currently doing but slightly less jerkily: fixed point. A 32 bit position value can represent values 0 through 4,294,967,295 even though your screen almost certainly has less than 4k pixels along either axis. So put a fixed "binary point" (by analogy with decimal point) in the middle and you can represent pixel positions from 0-65536 with another 16 bits of subpixel resolution. You can then add numbers as normal, you just have to remember to convert by right shifting 16 bits whenever converting to screen space or when you've multiplied two numbers together.

(I wrote a 3D engine in 16-bit fixed point back in the day when I had an Intel 386 with no floating point unit. It achieved the blinding speed of 200 Phong-shaded polygons per frame.)
> 1 votes

# Answer
In addition to the other answers here you can use dithering to some extent. Dithering is where the edge of an object's pixels are lighter/darker in color to match the background making for a softer edge. For example, say you had a 4 pixel square I'll aproximate with:

```
OO
OO

```

If you were to move this 1/2 a pixel to the right, nothing would really move. But with some dithering you could make an illusion of movement a bit. Consider O as black and o as gray, so you might do:

```
oOo
oOo

```

In one frame and

```
 OO
 OO

```

In the next. The actual "square" with the grayed edges would actually take 3 pixels across, but since they are lighter gray than the black they appear smaller. This can be difficult to code, however, and I'm not really aware of anything that does this right now. About the time they started using dithering for things resolutions quickly became better and there wasn't as much need except in such things as image manipulation.
> 1 votes

---
Tags: sprites, movement, pixel
---


# Question
Title: GUI Text counter Skips numbers after a few seconds
The counter counts perfectly up until the first bump. After this it starts to add about 4-5 "points" instead of just 1.

```
using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour
{

    public GUIText scoreText;
    public int score;

// CONVERT FLOAT TO INT?

    void Start (){
    score = 0;
    StartCoroutine (FeetScoreCounter());
    }

    // STARTS COUNTING AFTER WAITFORSECONDS
    IEnumerator FeetScoreCounter() {
    yield return new WaitForSeconds (1);
    InvokeRepeating("scoreCounter", 2, 1);
}

// FOR EACH 5 SECONDS; score++ ???

    void Update () {
    scoreText.text = score + " ft";
 //     StartCoroutine (FeetScoreCounter());

}

void scoreCounter () {
    score += 1;
    StartCoroutine (FeetScoreCounter());
    score ++;
}

}

```

I want my counter to start counting when the game starts, to show how far up the balloon is. I am incapable of seeing why my code just randomly adds a whole lot more over time. Care to help?

# Answer
It looks like you have your score working using `Time.time` as the counter.

I thought it may be helpful to explain what was happening when the code in your question is executed.

1. When game starts and the `Start()` method runs it calls `StartCoroutine (FeetScoreCounter())`
2. When `FeetScoreCounter()` runs it immediately yields for one second, then after that delay it calls `InvokeRepeating("scoreCounter", 2, 1)`. This will cause `scoreCounter()` to run repeatedly starting after a two second delay, and then again every second.
3. When `scoreCounter()` runs it: A) increments `score`, B) calls `FeetScoreCounter()` (see step 2) , and then C) increments score again.

The first time `InvokeRepeating("scoreCounter", 2, 1)` is executed it causes `scorecounter()` to run in a repeating manner: wait couple of seconds then once per second until canceled.

Each subsequent call of `InvokeRepeating("scoreCounter", 2, 1)` has the same effect, but the earlier ones are never canceled.

Each time `scoreCounter()` runs it calls `FeetScoreCounter()` (and `InvokeRepeating()`) triggering an additional call of `scoreCounter()` to occur each second from then on.

As a result you quickly have many parallel `InvokeRepeating()` requests each calling `scoreCounter()` on a regular schedule. This will cause the score to increase at an exponential rate.

---

An alternative implementation might look like this:

```
public class GameController : MonoBehaviour {

    public GUIText scoreText;
    public int score;
    public int delay = 2;
    public int frequency = 1;

    void Start () {
        score = 0;
        InvokeRepeating("scoreCounter", delay, frequency);
    }

    void scoreCounter () {
        score++;
        scoreText.text = score + " ft";
    }

}

```
> 1 votes

# Answer
This was the correct solution, where it converts score (float) to an integer.
> 0 votes

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


# Question
Title: Unity, Cannot change a single Vector2 element of mesh.uv?
I have a simple procedurally generated mesh, with uvs that tile correctly

```
for(int i=1; i<vertices; i++) {
    uv[i] =  new Vector2(x,z);  //pseudocode
}
mesh.uv = uv;

```

This works fine. However if I later attempt to change one of the mesh.uv entries

```
for(<loop over four nodes on tile>) {
    Debug.Log("before: " + mesh.uv[vertex_index].ToString()); // print before

    mesh.uv[vertex_index] =  new Vector2(new_x,new_y);

    Debug.Log("after: " + mesh.uv[vertex_index].ToString()); // print after
}

```

**I get no change in mesh.uv.**

What am I missing about unity mesh storage? This works fine for a simple array of Vector2:

```
Vector2[] v2 = {Vector2.one, Vector2.one};
for (int j = 0; j < 2; j++) {
    Debug.Log(v2[j]);
    v2[j] = new Vector2(2,3);
    Debug.Log(v2[j]);
    }

```

**EDIT:** I can make a successful uv-change by making a copy of the mesh.uv, changing the Vector2 values in the copy and then assigning mesh.uv = copy.

```
Vector2[] uvCopy = mesh.uv;
for(changed vertices) {
    uvCopy[vertex_index] = new Vector2(new_x, new_y);
}
mesh.uv = uvCopy;

```

I still would like to know what was wrong with my original approach, if anyone has any ideas.

# Answer
> 2 votes
I'm fairly certain, though someone will no doubt prove me wrong, that you can not change individual elements in the mesh arrays of vertices, triangles, uvs etc. That is why when you work with procedural meshes you always update the entire array at once when you've finished modifying it.

The reason for this is that mesh.uv gives you a copy of the mesh uvs array or assigns the uvs array, it doesn't allow you to directly modify individual uvs because you're not actually modifying the uvs on the mesh, you're modifying a copy.

---
Tags: c#, unity, uv-mapping, mesh
---


# Question
Title: Need help in tracking down memory leak in Unity standalone game
I'm experiencing a memory leak in my Unity game. If the game sits idly (no new game objects are being created in the scene), Windows Task Manager will show the memory of the .exe slowly rising.

I've attached the Unity profiler and the memory profiler stays completely flat with no new objects being created and its reported memory numbers don't rise. Thus, I assumed it must be from garbage allocations each frame somewhere. So I check the CPU profiler and there were a few scripts that were showing a few bytes of GC Alloc, most of which I've fixed. However, the memory leak appears to still be present.

I've gone as far as systematically removing objects from the scene to see if the memory leak stops, but that hasn't proven fruitful.

What's the next step to take to track this down? What other tools can I use?

I'm also noticing that the amount of memory being released between scene changes isn't great (very little in fact, even after requesting a GC collect). I'm hoping this is related to the memory leak during the scene though.

# Answer
> 1 votes
Memory leaks in Unity can occur on several places. But to help you in the right direction, one of the most common leaks in unity would be the

* Texture/ material leaks
* Imperfect loops (for, foreach, while, etc)

These leaks are often hard to track and can lead to crashes. To properly chase them down you first want to make sure that you have no warning message, and no errors. Make sure that warnings are not ignored using #pragma's and the likes, and run some form of code analysis over your codes.

After making sure your code has no errors/warnings you will want to check your textures and materials. They fairly often lead to leaks, in several different ways such as Renderer.materials. Static references to materials/textures can also lead to leaks, and the same counts for singletons if not properly cleaned up after.

If even after this information you are still unsure to where the leaks came from, you will either need to provide some source, or check out the #unity3d IRC. which has quite the helpful community (and off course if you find the answer there, don't forget to post it here as well for other people to find)

---
Tags: unity, memory, profiling
---


title: Box2d polygon skin

text:
# Question
Title: Box2d polygon skin
In manual is see:

> Polygons inherit a radius from b2Shape. The radius creates a skin around the polygon. The skin is used in stacking scenarios to keep polygons slightly separated. This allows continuous collision to work against the core polygon. The polygon skin helps prevent tunneling by keeping the polygons separated.

From this I don't understand what problem is being solved with the skin? What if there were not skins, what would happen?

# Answer
> 0 votes
Polygon skin is used in Continuous Collision Detection (CCD) and is something internal to Box2D.

As says Erin Catto:

> Polygon skin is a buffer for continuous collision detection. CCD breaks down when shapes overlap. Need a small separation. You shouldn't need to tune it if you use meters.

Here is more information how CCD works in Box2D.

---
Tags: box2d
---


# Question
Title: Cocos2d-x how to draw in specific free form area
Here https://github.com/mikeccy/cocos2dx-finger-paint/blob/master/Classes/HelloWorldScene.h and https://github.com/mikeccy/cocos2dx-finger-paint/blob/master/Classes/HelloWorldScene.cpp you can see how a Sprite is being rendering in RenderTexture. What I want to add to this to make visible only the specific part in RenderTexture (canvas). I.e. I should apply a free form mask on it to be able to draw in a specific free form area.

How to do this in cocos2d-x 3.2?

# Answer
> 0 votes
Here is the answer in cocos2d-x forum: http://discuss.cocos2d-x.org/t/cocos2d-x-how-to-draw-in-specific-free-form-area/17623

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


# Question
Title: Algorithm for procedural 2D map with connected paths
**Problem to solve:** Generate a random 2D dungeon map for a tile-based game where all rooms are connected.

I am looking for better solutions than what I currently have.

My current solution is that I run two algorithms. The first generates the dungeon with its rooms. The second makes sure that all rooms are connected. I am curious what other solutions may exist. Faster and / or easier etc. Speed is not really a concern, but if speed can be gained at no real cost, well, that is a good thing. More important is that I, and others that read, may learn different ways to approach and solve the problem.

Below is my current implementation. Rooms currently have no exits or exits in any 2, 3 or 4 directions.

**Generating the dungeon rooms**

Setup: Set the current room to the top left room.

1. Get a valid room type for the room (where valid room type is a type with no exits out of the dungeon and that have exits that match the exits of the room above and the room to the left. Only need to check above and to the left due to step 2 below).
2. Put down the room and advance the x-coordinate one step. If the x-coordinate exceeds the dungeon width, set the x-coordinate to 0 and advance the y-coordinate one step. If the y-coordinate exceeds the dungeon height, we are done.
3. Repeat from #1.

I then check to see if all rooms are connected. If they are not all connected, I run a second algorithm that, in a non-sexy but definitely good enough way in terms of dungeon layout, goes through the rooms and changes them so that all end up being connected.

**Checking to see if all rooms are connected**

Setup: Create a 2D map of integers representing paths and initialize the entries to an "unprocessed" (not yet traversed) value, -1. Set a start path index integer that keeps track of the current path to 1. Set the current room to the top left room by adding it to a stack of rooms to check.

1. If the stack contains rooms to check, pop it set the path index of the room to the current path index. If the stack does not contain any rooms, increase the path index and try to get a room by advancing column by column, row by row, until we get a room that has not been processed yet. If no room can be found, we are done.
2. Check to see if the room has an exit to the left. If it has one, add the left room to the stack if it is not already there.
3. Repeat step 2 for down, right and top directions (since we are using a stack, that means the rooms are traversed in clockwise order, starting with the top direction).
4. Repeat from step 1.
5. If the path indices count is greater than one, there are disconnected rooms.

If there are disconnected rooms I then group the rooms by their path index, get the index of the biggest path and connect all other rooms to those rooms. This is a work in progress, but my (current, "brutish") plan is to go through each room in a room group (except the first), check to see if there is a horizontal or vertical path to the biggest room group, and if so, create a horizontal / vertical path there by injecting / updating the rooms in between. Rinse and repeat. Ugly, yes, but it is something that will not be noticeable in terms of visual pattern so it works in that sense.

# Answer
One of the best, and most used, algorithms I've seen out there is generating dungeons using Binary Space Partitioning.

The best general explanation I've read is the one found in The Chronicles of Doryen (attached at the end for backup purposes) because explains the procedure without getting into the code, thus leaving the implementation to the reader.

Two other tutorials on the same subject, with code, can be found at

---

> ## Building the BSP tree
>
> We start with a rectangular dungeon filled with wall cells. We are going to split this dungeon recursively until each sub-dungeon has approximately the size of a room. The dungeon splitting uses this operation :
>
> * Choose a random direction : horizontal or vertical splitting
> * Choose a random position (x for vertical, y for horizontal)
> * Split the dungeon into two sub-dungeons
>
> Now we have two sub-dungeons A and B. We can apply the same operation to both of them.
>
> When choosing the splitting position, we have to take care not to be too close to the dungeon border. We must be able to place a room inside each generated sub-dungeon. We repeat until the lowest sub-dungeons have approximately the size of the rooms we want to generate.
>
> ## Building the dungeon
>
> Now we create a room with random size in each leaf of the tree. Of course, the room must be contained inside the corresponding sub-dungeon. Thanks to the BSP tree, we can’t have two overlapping rooms.
>
> To build corridors, we loop through all the leafs of the tree, connecting each leaf to its sister. If the two rooms have face-to-face walls, we can use a straight corridor. Else we have to use a Z shaped corridor.
>
> Now we get up one level in the tree and repeat the process for the father sub-regions. Now, we can connect two sub-regions with a link either between two rooms, or a corridor and a room or two corridors.
>
> We repeat the process until we have connected the first two sub-dungeons A and B
> 35 votes

# Answer
The **BSP method** is apparently the most popular method for generating dungeons, but it's not the only one.

For completeness I'll explain the generator that worked for me. I have to admit that I don't recall where I read about this so I'll just say that it's not my invention (an old article by Jamis Buck sounds very familiar).

## A maze with rooms

The basic idea is that a dungeon is a maze with rooms, sort of. So the first step for this algorithm, is to generate a maze:

The next step is to make it sparse (remove dead ends):

Step number 3 is to add some loops (make it non-perfect) but I'll skip the image because it's barely noticeable (I didn't need a perfect maze so I took a few shortcuts on the maze generation algorithm, so it already had loops by this point).

Then, for step 4, we need to remove isolated cells:

At this point we're done with the corridors and we're ready to add rooms. For that we do the following:

1. Generate a set of rooms (width and height)
2. For each room we iterate through all possible locations and decide the best location.
    * The best location is calculated by adding a weight to conditions (such as adjacency to a corridor).
3. We place the rooms.

So far, our dungeon will look like this:

The final step is to add decorations.

## Some final thoughts

* I used a stripped-down version of the Eller Algorithm.
* Different maze algorithms may result in different textures. You might prefer another algorithm. For example, the following image shows different *textures* resulting from "Binary Tree" (diagonal bias) and a variation of "Recursive Division" (long corridors) algorithms:
> 4 votes

---
Tags: 2d, procedural-generation, tilemap, random
---


# Question
Title: Andengine onAreaTouched TouchEvent not working - ACTION_OUTSIDE & ACTION_CANCEL
I have a simple problem. I have a button on the screen. I want isActionDown to push the button down, and isActionUp to push the button back up again and make my character jump. But the problem is if I push the button down and drag away from it, the button stays pushed down. I would like the button to push back up again if the user drags away from it.

How can I create the desired affect? isActionCancel doesn't seem to do the trick.

```
    private void addButton(){
goB = new AnimatedSprite(240, 364, ResourceManager.getInstance().go_region, vbom){
    @Override
    public boolean onAreaTouched(final TouchEvent event, final float x, final float y){

        if (event.isActionDown()){
            goB.animate(new long[]{ 250 }, new int[] { 1 }, true);
            /*if(event.isActionCancel()){
                goB.animate(new long[]{ 250 }, new int[] { 0 }, true);
            }*/
        }
        if (event.isActionUp()){
            goB.animate(new long[]{ 250 }, new int[] { 0 }, true);
            fresh = true;
            playerBody.applyLinearImpulse(new Vector2(0, 45), playerBody.getPosition());
        }

        if (event.isActionCancel() || event.isActionOutside()){
            goB.animate(new long[]{ 250 }, new int[] { 0 }, true);
        }
        return true;
    }
};
goB.setScale(3);

registerTouchArea(goB);
attachChild(goB);

goB.animate(250);
}

```

I'm having the hardest time with this, and I've tried all sorts of variations of the code above. Please let me know if you have the solution.

Thanks for your help!

# Answer
`onAreaTouched` Is triggered when the button is pressed, and that press is inside its bounds. This means the event will never be `isActionOutside()` or `isActionCancel()`, because a button simply wouldn't receive events like this.

You need to have a global listener that listens for events. All your components talk to your global listener and the global listener watches for events that are outside the bounds of your components. For example, you'd have your button notify the global listener that it's being pressed, then if the global listener hears about another event that's not inside the button's bounds (like an `ActionUp` event), the global listener can tell the button that it's no longer being pressed.

This is a common problem with event systems. It's more complex to remember who received what event and if they should be notified about future events based on the initial event type. That's why it's up to you to write this functionality if you want it.
> 1 votes

---
Tags: java, android, software-engineering, andengine, events
---


# Question
Title: Place tile values over 'chunk' boundries
My game has a 'chunk' engine similar to Minecraft's but in 2 dimensions. Each chunk is a square of 32 by 32 tiles.

What I want to do is generate a defined shape across multiple chunks without breaking the shape.

This is made difficult by the fact that chunks are generated one chunk at a time in unknown intervals of time, so I cannot place a structure after the amount of chunks it needs to fit in are generated, as the player might move into the area before that time.

Another problem is that I cannot simply tile the shape uniformly because the shape needs to be exactly one tile above the surface, which is a heightmap generated using simplex noise, so it is not flat.

Is there any way I can generate this structure from one point of origin placed at random intervals over a heightmap that is known?

Example of what I want:

Grey Lines - chunk bounds

White Tiles - structure generation

Blue Tiles - known 1D heightmap

How can this be done?

# Answer
I have also implemented a chunked engine. The best way to think of it is to just think of the chunks as *memory storage locations* rather than as *actual structures* of the world. Then, whenever you generate content, generate it as though you had a giant array of arbitrary size.

Just implement some functions like

```
Voxel* GetVoxelAt(int x, int y, int z);

```

Which will end up looking like this:

```
Voxel* GetVoxelAt(int x, int y, int z)
{
    Chunk* chunk = GetChunkAt(x, y, z);

    if (chunk) return chunk->GetVoxelAt(x, y, z);
    else return NULL;
}

```

Then you can happily do all of your generation, logic, etc. in the global space without having to worry about chunks. Now as for your question of *time*, well you need to defer any generation you do to another system that waits for the chunk to exist. You can simply generate the chunks whenever content needs to be placed there, for instance, or you can just put the content on a "To generate" list that gets checked whenever the chunk that's needed gets created.

Another option is to store all of your content as "templates" in the global space. When chunks get generated, they check each of the templates to see if they intersect them. If they do, the content gets generated there.

In my game, I just have a list of templates, and each template is just a list of voxel relative to some other voxel. I also have a hack called "pillars" which place voxels all the way from the bottom of the template to the land so that all structures are "supported". Then, when I generate a new chunk, I iterate through the incomplete templates to find one that intersects the chunk. Then, I place all of the blocks and pillars that the template specifies in the new chunk, and mark those blocks as completed. When all the blocks in a template are completed, its removed from the template list.

**EDIT** Template list example pseudocode:

```
// Represents a 2D template of voxel types.
class Template
{
    int sizeX;
    int sizeY;
    VoxelType[][] values;
}

// Represents a template at a specific location
class TemplateInstance
{
    Template template;
    bool[][] completed;
    int xLocation;
    int yLocation;
    Set<ChunkID> intersectingChunks;

   // Compute all potential chunks that could intersect this template
   void ComputeIntersectingChunks()
   {
        for (int x = xLocation; x < template.sizeX + xLocation; x++)
        {
             for (int y = yLocation; y < template.sizeY + yLocation; y++)
             {
                 ChunkID id = GetChunkIDAt(x, y);

                 if(!intersectingChunks.contains(id)) intersectingChunks.add(id);
             }
        }
   }

   // Add this instance to a hash map of all chunks to list of instances
   void AddInstance(HashMap<ChunkID, List<TemplateInstance> > instances)
   {
       for (ChunkID id in intersectingChunks)
       {
           instances[id].add(this);
       }
   }

   // Remove this instance from the hash map of instances
   void RemoveInstance(HashMap<ChunkID, List<TemplateInstance> > instances)
   {

      for (ChunkID id in intersectingChunks)
      {
          instances[id].remove(this);
      }
   }

   // Given a specific chunk, generate all the voxels in that chunk
   // belonging to this instance (does not include "pillars")
   void Generate(Chunk chunk)
   {
        for (int dx = 0; dx < template.sizeX; dx++)
        {
             int x = dx + xLocation;
             for (int dy = 0; dy < template.sizeY; dy++)
             {
                 int y = dy + yLocation;
                 if(!chunk.Contains(x, y)) continue;
                 Voxel* voxel = chunk.GetVoxelAt(x, y);
                 voxel.type = template.values[dx][dy];
                 completed[dx][dy] = true;
             }
         }

   }

   // True when all the voxels have been placed.
   bool IsComplete()
   {
      return *all completed*
   }
}

// Outer function generates all the templates intersecting a chunk
void GenerateTemplates(Chunk chunk, HashMap<ChunkID, List<TemplateInstance> > instances)
{
    List<TemplateInstance> intersecting = instances[chunk.ID];

    for (TemplateInstance template in intersecting)
    {
        template.Generate(chunk);
        if (template.IsComplete())
        {
           template.RemoveInstance(instances);
        }
    }
}

```
> 1 votes

---
Tags: tiles, procedural-generation, data-structure
---


# Question
Title: How do I tell if my enemy can see my player?
Given a player and an enemy with position, and given the direction vector of each, how can I tell if one can "see" the other?

In other words, how do I test if one position with direction is in front or behind another position with direction?

For my purposes, 'in front of' means directly in front of, or 90 degrees to either side.

# Answer
> 18 votes
The dot product of two vectors can tell you if they face each other or not. First vector can probably be the enemies view direction the second one should be a vector pointing from player's position to the enemies position.

https://www.youtube.com/watch?v=Q9FZllr6-wY

---
Tags: mathematics, ai, vector
---


# Question
Title: Setup VertexPositionTexture array for a texture2D at a location
I am trying to adjust the following code to render a quad on a 2D texture at a specific location and specific size. Currently this code will render a fullscreen quad, which makes sense since the `POSITION` semantic is being set to the fullscreen size.

My issue, is that I don't know how to adjust the `POSITION` semantics in the declaration below to use the specified location and size of a texture.

```
private short[] indexData = new short[] { 0, 1, 2, 2, 3, 0 };

private VertexPositionTexture[] CreateTriangles(Vector2 location,
                                                float width, float height)
{

    // how do I get these values, and where do I set them below?
    float topleft = ??;
    float topRight = ??;
    float bottomLeft = ??;
    float bottomRight = ??;

    VertexPositionTexture[] vertices = new VertexPositionTexture[]
    {
        new VertexPositionTexture(new Vector3(1f, -1f, 0f),
                                  new Vector2(1, 1)),
        new VertexPositionTexture(new Vector3(-1f, -1f, 0),
                                  new Vector2(0, 1)),
        new VertexPositionTexture(new Vector3(-1f, 1f, 0),
                                  new Vector2(0, 0)),
        new VertexPositionTexture(new Vector3(1f, 1f, 0),
                                  new Vector2(1, 0))
    };

    return vertices;
}

```

All I'm trying to do is render a quad overtop of a texture at a specific location. If I use the code as-is with my texture is will stretch the texture to the entire size of the screen (again, makes sense because of how the `POSITION` semantic is being set).

# Answer
> 0 votes
I figured it out. Hopefully this can help someone else.

```
private short[] indexData = new short[] { 0, 1, 2, 2, 3, 0 };

private VertexPositionTexture[] CreateTriangles(Vector2 location,
                                                int width, int height)
{
    /* this is what the index data tells us
     *
     * 2  ________________ 3
     *   |\               |
     *   |  \             |
     *   |    \           |
     *   |      \         |
     *   |        \       |
     *   |          \     |
     *   |            \   |
     *   |              \ |
     *   |________________|
     * 1                   0
     *
     */

    float bbw = this.gfx.PresentationParameters.BackBufferWidth;
    float bbh = this.gfx.PresentationParameters.BackBufferHeight;

    float left = -(((bbw / 2f) - location.X) / (bbw / 2f));
    float top = (((bbh / 2f) - location.Y) / (bbh / 2f));
    float right = -(((bbw / 2f) - (location.X + width)) / (bbw / 2f));
    float bottom = (((bbh / 2f) - (location.Y + height)) / (bbh / 2f));

    // this is how the triangle points are specified
    VertexPositionTexture[] vertices = new VertexPositionTexture[]
    {

        // point 0
        new VertexPositionTexture(new Vector3(right, bottom, 0f),
                                  new Vector2(1, 1)),

        // point 1
        new VertexPositionTexture(new Vector3(left, bottom, 0f),
                                  new Vector2(0, 1)),

        // point 2
        new VertexPositionTexture(new Vector3(left, top, 0f),
                                  new Vector2(0, 0)),

        // point 3
        new VertexPositionTexture(new Vector3(right, top, 0f),
                                  new Vector2(1, 0))

    };

    return vertices;
}

```

# Answer
> 0 votes
In the code here :

```
new VertexPositionTexture(new Vector3(1f, -1f, 0f),
                                  new Vector2(1, 1)),
        new VertexPositionTexture(new Vector3(-1f, -1f, 0),
                                  new Vector2(0, 1)),
        new VertexPositionTexture(new Vector3(-1f, 1f, 0),
                                  new Vector2(0, 0)),
        new VertexPositionTexture(new Vector3(1f, 1f, 0),
                                  new Vector2(1, 0))

```

You try to adjust the Quad Size, by defining 4 points. Depends on whether you try to define them in clockwise or counterclock wise, you can set the positions , topleft, tobRight, BottomLeft, BottomRight instead of those 4 points.

---
Tags: xna, shaders, vertex
---


title: InputManager in Unity

text:
# Question
Title: InputManager in Unity
I´m having a rough time trying to figure out a proper way of dealing with key mapping and key bindings in unity. The built-in unity input manager is useless to me since it doesnt support key mapping ingame and you cant acces it via script, you can only change your key bindings on the game laucher, but not ingame.

I guess I will need to create my custom InputManager to replace the unity one but im pretty much lost in this matter. So far I´m beein doing some research and now I know how to create a basic but robust input manager in C++ (thanks mainly to this tutorial http://www.gamedev.net/blog/355/entry-2250186-designing-a-robust-input-handling-system-for-games ) But as i said I dont know how to translate this into unity c#.. My first idea was to create a complete new input manager from scratch that use an xml file to store the key binding data, but I dont know if you think this is the wrong way to follow. First of all I dont even know how could I acces RawInput in unity. Checking the script documentation was of no use in this matter, i found something about keyboard events but they only work under OnGUI function and I dont know if i should use it then...

I know there are some commercial plugin out there for that solve this purpose but thats not the point, I´m trying to do it this by myselft

Could someone explain to me how could I make my own InputManager from scratch or give me some indication to put me in the right way to this?

I apologize for my bad english btw

-EDIT FOR CLARIFICATION:

Im trying to achieve just the typical key mapping menu but I must be able to access this menu ingame, i mean, via pause menu. ingame-\>pause menu-\> options-\> controls. for example, I have the jump action mapped to the space bar, In my controls menu I select remap this this action. A dialog propt and wait for me to press the new key to map to the jump action. I press ctrl (or whatever key)...and then I update the dictionary, jump action = ctrl (or whatever keycode it is). But the issue is, how do I know which key did I just pressed while the dialog waiting for a new key was active? Should I use something like:

```
void OnGUI() {
    Event e = Event.current;
    if (e.isKey && remapping)
        remap(action, e.keycode);

```

or if not just a bunch of if statements, one for each keycode of the keyboard i mean

`if Input.getKey('keycode')
 remap(action, keycode);`

what surely will work but just use about 100 if statemens

I hope I explained myself clearly now. Anyway I was doing some research before start writting any code but I will do a script what I thought so far and then post it for a better understanding.

# Answer
Unity allows you to get individual key down events via the Input.GetKey function, and the appropriate key enum. Additionally, it supports axis information via the Input.GetAxis function.

If you want to build an input map around this, then you could write an input manager that sits "in between" the unity input events, and your own event system. An input map would esentially be a one to one or one to many relationship of input events, to unity key events. Updating which keys are tied to which events could be very reasonable achieved. The simplest way to do this would be to store a dictionary of KeyCodes, and a list of the events they are registered with, and simply update these event lists if necessary. Additionally, serializing this information to an xml file would not be unreasonable at all, especially with the extensive and easy to use system that .net provides.
> 4 votes

# Answer
The story like this.... Unity Input Manager pain is lasting for years. On Unity site you can find request on the forum for InputManager programmatic access dating from 2004, and feedback from 2009 with state planned today 2014.

https://youtu.be/Pir49v16aOQ

Below are some of the problems.

1) Ingame input controller mapping. Unity have user interface for mapping predefined bindings at start the of game. Changing mapping later need game restart.

2) Handling input in code based on states/tag abstracting real input. Some sort of abstraction is done thru InputManager well known "Horizontal" and "Vertical", but that abstraction is still bonded to axes and buttons and not to actions/states of the game(one of those might be AnimateStates of Mecanima).

3) Saving and restoring user preferences PlayerPref might do the trick if you not plan to support Web, Droid and if file size is not bigger then 1 megabyte. File type that can be readable by humans and machines, and easy exchangeable( players can exchange their game settings) between them might be XML.

4) Recognize positive and negative part of the axis. Unity recognize Axis as whole part and gives value 1 \<--- (-1) ---\> 1. It is expected to gives value from 1\<---- (0) ----\> -1, so turning left/right on wheel input controller or joystick push/pull forward/backward can be achieved, trigger shooting rapid fire... .

5) OS independent driver and easy expansion with drivers supporting other devices and special properties Unity internal input handler might not recognize the controller or it will identify layout in different system differently and would not offer support of device extra features like force feedback, IR pointer, accelerators, gyros ...of modern input controllers. So instead of use pluggin-paid OS dependent drivers, seem much better OS dependent HID interfaces with OS independent pluggable drivers.

6) Handling input axis and buttons as digital or analog In Unity thru Input class you can handle axes only as analog and buttons as analog/digital. Its handy to have axes as digital events UP,DOWN ,HOLD...

7) Create combination of inputs that would trigger action/state Unity doesn't offer out of the box combining input action like 2 keys in row,button press and axis move, ....like in fighting game scenario 2times joystick left + fire (Mustafa kick Cadillacs and Dinosaurs)

8) Handling inputs by events Seem whole Unity engine is not much planned as event, signal or reaction based system and encouraging of use of Broadcast messaging and handling complex input inside Update is far from good solution even if you need last processor ns.

9) Plug and play instead of plug and pray. Attach or remove controllers while game is running and continue playing. If you using "Any joystick" option hot seat multiplayer isn't an option. Joystick numeration might be change on while replugged.

10) Profiles - Layouts.....

If you expect few lines of miracle code u can dream of it. So the answer is make robust clean solution or use some of existing. From existing don't use that one like CInput or InControl that are wrappers of Unity InputManager would get same hackish trouble soon... You can try Rewired or you can try my solution so you not reinvent the wheel First you can start mapping even in editor.Save.

and then remap in game.Save.

works with OSX,Win,Droid and Web

1) Ingame input controller mapping. Input Mapper allows you easily to map game controller input to Animation States from your Animation Controller or custom states

7) Create combination of inputs that would trigger action/state Map inputs to state by just clicking keys/mouse/buttons or moving joystick as SINGLE, DOUBLE and LONG and make combination of inputs(Combos). Primary and secondary. In bellow example I've map to Wave state combo of Mouse0 double clicks + Joystick1AxisYNegative (Long pull backward of the Joystick) + double click of letter Y.

You can set modifier format or clicks sensitivity.

3) Saving and restoring user preferences Saving would export your settings to .xml file and States.cs will be generated containing enum of your mapped states.

```
public enum States:int{
         Wave=1397315813,
         MyCustomState=-1624475888,

```

Now you can forget about:

```
//  static int idleState = Animator.StringToHash("Base Layer.Idle");
//  static int locoState = Animator.StringToHash("Base Layer.Locomotion");
as we are tought in Unity tutorials, but you can use States.[some state].

```

Library contains simple component so you can test user perspective right away. Just drag saved .xml and Play.

2) Handling input in code based on states/tag abstracting real input. InputMapper API are very similar to Unity API's with the big difference and that is abstraction on 2 levels.First you not program with real inputs like KeyCode.Q or Joystick1Button99, but with states which also allows player to map different input to same action state.

```
if(InputManager.GetInputDown((int)States.Wave)){
  Debug.Log("Wave Down");
   }

 if (InputManager.GetInputUp((int)States.MyCustomState))
            {
                Debug.Log(States.MyCustomState + "-Up");
                // animator.Play((int)States.Wave);
            }

//atOnce (default=false)
//Function returns true when combination pressed in row  If set to true function return true
//when all keys/buttons in combination are pressed.
bool bCombo = (InputManager.GetInput((int)States.Click_W+C_State, atOnce
));

```

4) Recognize positive and negative part of the axis. System recognize Forward,Backward,Left,Right of POV axis and Positive/Negative of normal axes.

6) Handling input axis and buttons as digital or analog Second abstraction is that you can use digital or analog output no matter your real input source is digital or analog meaning for ex. Joystick Axis count as analog source can produce normalized values from 0 to 1, but also pushed true/false, or key or even mouse button.

```
//using input as digital
bool bHold=(InputManager.GetInput((int)States.Walk_Forward,false));

//using input as analog value
float analogValue=InputManager.GetInput((int)States.Walk_Forward,false,0.3f,0.1f,0f);

```

8) Handling inputs by events As Update method get overcrowded, library offer modern input handling solution by use of Event based system.

```
     //Event Based input handling
           InputEvent ev = new InputEvent("Click_W+C_State");
         //InputEvent ev = new InputEvent((int)States.SomeState);

           ev.INPUT += new EventHandler(Handle1);
           ev.INPUT += new EventHandler(Handle2);
           ev.UP += new EventHandler(onUp);//this wouldn't fire for combo inputs(single only)
           ev.DOWN += new EventHandler(onDown);//this wouldn't fire for combo inputs(single only)
}

   void onUp(object o, EventArgs args)
   {
       Debug.Log("Up");
   }

   void onDown(object o, EventArgs args)
   {
       Debug.Log("Down");
   }

   void Handle1(object o, EventArgs args)
   {
       Debug.Log("Handle1");
   }

   void Handle2(object o, EventArgs args)
   {
       Debug.Log("Handle2");
   }

```

Hardcode developers can manually map input to states and even mix with loaded settings.

```
InputManager.loadSettings(Path.Combine(Application.streamingAssetsPath,"InputSettings.xml"));

//adding input-states pairs manually
InputManager.MapStateToInput("My State1",new InputCombination("Mouse1+Joystick12AxisXPositive(x2)+B"));

InputManager.MapStateToInput("Click_W+C_State", KeyCodeExtension.Alpha0.DOUBLE,KeyCodeExtension.JoystickAxisPovYPositive.SINGLE);

```

In KeyCodeExtension all KeyCode stuff are supported plus additional for Joystick Axis mapping.

5) OS independent driver and easy expansion with drivers supporting other devices and special properties I understood Unity couldn't support all game devices but some system that allows simple binding of driver might be good idea (Yeah they have pluggins.....).
So instead building pluggins for all OSes, you use InputMapper system built-in mini HID interface systems for (Win,Web,Droid and OS) and OS independent driver. (Yes you can make C driver and compile in anything...) Device would be handled by default driver (WinMMDriver for Win and OSXDriver for OSX) or by custom driver if added like this:

```
//supporting devices with custom drivers
   InputManager.AddDriver(new XInputDriver());

```

Your implementation of custom device driver had 2 entry points that need implementation:

```
(1)public IJoystickDevice ResolveDevice(IHIDDeviceInfo info)...

(2)public void Update(IJoystickDevice joystick)...

```

ResolveDevice where HIDInterface provide device info from the OS, you can check VID and PID to decide to handle and init device properties and structures, or not returning null, and Update function to query device by use of provided Read/Write methods methods and fill the JoystickDevice structures, so can be accessed by InputManager. Scare about handling few bytes??? :)

Originally OS implementation of ResolveDevice point is by using Report HID Page from device description, but that restrict using devices that aren't planned to work with that OS, like Wiimote,Xbox Gamepad... In Input Mapper you need simply to extend JoystickDevice Class, which already contains some basic functionality supporting axes and buttons, by adding specialized properties of device you are planning to support.

Update point is synchronization point with Unity. System use high level synch and async ReadXXX methods and return buffered byte array. What each of bytes means is easy to decipher as there are many web sites about any devices. Developer task is to fill JoystickDevice structure with values processed from byte array returned. Write methods are used for setup the device...like light leds, start FFD, enable disable....

Still want to use Unity InputManger as backup

InputManager.AddDriver(new UnityDriver());//(-1 to 1 to -1) Swap your InputManger.asset with InputManager.asset from github source code.

Devices used during testing: XBox360W controller, ThrustMaster Wheel FFD, Wiimote + Nunchuk. One classic Gamepad controller, one Wheel and complex controller.
> 2 votes

# Answer
Im not sure if this will work, I haven't actually tested it.

```
public abstract class KeyInputController{

  public  char forward = 'w';
  public  char backward = 's';
  public  char left = 'a';
  public  char right = 'd';

  //Add more

  public abstract void moveForward();
  public abstract void moveBackward();

  //Add functions for each input

  public void Update()
  {
       if(Input.inputString!="")
       {
         //only works for first input,
         //if you want keys within the frame update,
         //you need to iterate over it, char by char.
         char input =Input.inputString[0];

         if(input == forward)
           moveForward();
         else if(input == backward)
           moveBackward();
         //Add checks for other inputs
      }
  }
}

```

Now you could write your keybindings to a simple text file. And just set those variables when you read them. ( havn't tried reading text/xml/json files in Unity but im sure it's possible )

The idea here is that the keys are stored in simple variables. Which you could easily change. It should be trivial then to read/write them away. So making an interface in game where you can set your keys shouldn't be a problem either.
> 0 votes

# Answer
You can use a Dictionary to map KeyCode to specific action, eventually you can change this at runtime:

```
using UnityEngine;
using System.Collections.Generic;
using System;

public class TestInput : MonoBehaviour {

    private Dictionary<KeyCode,Action> d;

    void Start ()
    {
        d = new Dictionary<KeyCode, Action>();
        d[KeyCode.A] = () => {Debug.Log("ACTION A");};
        d[KeyCode.S] = () => {Debug.Log("ACTION B");};
        d[KeyCode.I] = () =>
            {
                Action swap = d[KeyCode.A];
                d[KeyCode.A] = d[KeyCode.S];
                d[KeyCode.S] = swap;

            };
    }

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

        if (Input.GetKeyDown(KeyCode.A))
        {
            d[KeyCode.A]();

        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            d[KeyCode.S]();
        }
        else if (Input.GetKeyDown(KeyCode.I))
        {
            d[KeyCode.I]();
        }
    }
}

```

Btw it seems that Unity does't expose any method that returns a list of all pressed keys, so the code above isn't very elegant. Hope this help.
> 0 votes

---
Tags: unity, input, scripting
---


# Question
Title: How to improve Batch Rendering to work with 3D skeletal animation data
I've implemented a batch rendering technique that is described in detail here: http://www.gamedev.net/page/resources/\_/technical/opengl/opengl-batch-rendering-r3900

I'd like to extend it now to support 3D skeletal animation data, but I'm not sure what is the best way to do that so that the bone transformation can happen on the GPU rather than on the CPU. The Batches as they are defined right now depend on a transform matrix but that means that if I try to render a human, each limb would go into its own Batch, which means I would not get any performance gain by using the BatchManager as described in the article above.

Can someone suggest how to do batch rendering that works with 3D skeletal animation data?

# Answer
> 2 votes
The animation of skinned characters is usually performed using vertex shader constants. The model matrix is usually ignored, or used to define the local-to-world of the entire bone rig. Each bone is uploaded into a fixed, known constant offset. That same offset is cooked into the vertex data so that each vertex can extract the correct shader constant. In some cases there is one bone per vertex (rigid skinning) but in others there are more - they are blended together.

A quick search of the net found this example here:

http://mmmovania.blogspot.ca/2012/11/skeletal-animation-and-gpu-skinning.html

We render each skeletal model one at a time because we do per-model culling (hierarchical, but you end up with a single model) plus we split the models into parts anyways - on some platforms we run out of shader registers for the bones, or we have to switch materials. I imagine you could batch draw them in a special case by using a dependent read texture for bone data for crowd systems, perhaps, but that's a more bespoke solution.

---
Tags: opengl, rendering, skeletal-animation, batching
---


# Question
Title: Tools to generate convex collision geometry
Does anyone know tools to generate convex collision geometry from given 3D model?

For example, UDK's Static Mesh Editor can do this; Valve instead recommends to use smoothing in 3D editor.

Desired features:

1. The tool could convert concave geometry into convex shape automatically and remove unnecessary model data.
2. Could allow us to specify number of vertices/triangles in generated collision shape.
3. Could export that shape to some interchange file format (like COLLADA or FDX).

Does that tool exist? (it even can be commercial, not free, but could be obtained separately, without particular engine/SDK/bundle...)

# Answer
> 9 votes
I suggest automatically generating, and maybe caching, the convex collision meshes instead of creating them by an external tool. However, I am not sure which of the following ideas is what you want.

Do you want to end up with a single convex shape for a single model? That would be a *convex hull* around all vertices. Of course that simplification results in not that accurate collisions but on the other hand it is very fast compute them. Moreover, you have only one physics body per object which is faster than the alternative below.

Images are from http://cgtools.net/treatments\_convex\_hull.html.

Do you want to end up with several convex shapes for a single model? Then *convex decomposition* is what you want. For example Bullet Physics has an algorithm called HACD built in to perform convex decomposition. There is also a standalone version you could integrate in your own application. Furthermore, the algorithms allows you to specify the amount of detail and number of clusters in the result.

This screenshot is from the algorithm author's blog linked above.

# Answer
> 2 votes
V-HACD V2.0 provides better decomposition results than HACD. Check it out! http://kmamou.blogspot.ca/2014/11/v-hacd-v20-is-here.html

---
Tags: collision-detection, tools, content-generation
---


# Question
Title: Pygame's sprite.collide_circle() missing several frames of head-on collision
I've spent hours trying to figure why my collision detection was so crappy, with sprites visibly ovellaping for several frames, when I noticed the culprit could be pygame's detection callback `pygame.sprite.collide_circle()`.

I've stripped down the code and created a simple demo, and results were surprising: `collide_circle()` still returns `False` for several frames after its sibling `collide_rect()` correctly detects a collision and returns `True`.

Here is the code:

```
import pygame

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

SCREEN_SIZE = (800, 600)
FPS = 60
BG_COLOR = BLUE

class Ball(pygame.sprite.Sprite):
    def __init__(self, color=WHITE, radius=10, position=[], velocity=[]):
        super(Ball, self).__init__()

        self.color = color
        self.radius = radius
        self.position = list(position) or [0, 0]
        self.velocity = list(velocity) or [0, 0]
        self.bounds = (screen.get_size()[0] - self.radius,
                       screen.get_size()[1] - self.radius)

        self.image = pygame.Surface(2*[self.radius*2])
        self.rect = self.image.get_rect()
        pygame.draw.circle(self.image, self.color, 2*(self.radius,), self.radius)

    def update(self, dt=1./FPS):
        super(Ball, self).update()

        for i in [0, 1]:
            self.position[i] += self.velocity[i] * dt

            if self.position[i] < self.radius:
                self.position[i] = self.radius
                self.velocity[i] *= -1

            elif self.position[i] > self.bounds[i]:
                self.position[i] = self.bounds[i]
                self.velocity[i] *= -1

        self.rect.center = self.position

pygame.init()

screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.Clock()

background = pygame.Surface(screen.get_size())
background.fill(BG_COLOR)
screen.blit(background, (0,0))

balls = pygame.sprite.Group()
balls.add(Ball(color=RED,   radius=100, position=[  0, 300], velocity=[ 100, 0]))
balls.add(Ball(color=GREEN, radius=100, position=[700, 300], velocity=[-100, 0]))

done = False
while not done:
    for event in pygame.event.get():
        if (event.type == pygame.QUIT or
            event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            done = True

    balls.update()
    if pygame.sprite.collide_rect(*balls):
        collision = pygame.sprite.collide_circle(*balls)
        print collision
        if collision:
            for ball in balls:
                ball.velocity[0] *= -1

    balls.clear(screen, background)
    balls.draw(screen)
    pygame.display.update()
    clock.tick(FPS)

pygame.quit()

```

And the output:

```
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
True
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False

```

That's **17** frames of overlap before `collide_circle()` realizes that hey, there's a collision there! Even at 60 FPS that's huge.

The balls are almost halfway through each other, and this behavior seems to be velocity independent: if I change the balls' speed or the FPS, the visual result (halfway overlap) remains, but for fewer frames.

So, my question is: is this a pygame bug? Or did I completely misunderstood how detection works?

# Answer
Which version of PyGame were you using? An issue seems to have been fixed at some point between 1.9.1 and 1.9.2a concerning collide\_circle() (see here for fix diff).

It might be worth it to try 1.9.2a if possible (download/source here), which I believe isn't actually up on pygame.org. If you're on Linux or OS X you'll have to build 1.9.2a from source.
> 1 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: Uniform Block solve padding/alignment for vec3 in CPU struct
I have a struct on the CPU which I'm sending to a uniform block in my shader. After a bit frustration I finally got it to work. The problem I had was that vec3s are actually treated as 16-bytes, or in other words they need to have padding. So to solve this I added a dummy-float after each vec3 (see below).

I know I could just use vec4, but since I want to treat alpha as a separate component I don't want to type that 4th component for each vector every time. Furthermore, I would have to use swizzling in the shader as well to separate alpha.

Now to the question, is there any nicer/better way to solve the padding problem than having to add an extra float?

```
// CPU
struct Material
{
public:
    vec3 Emissive; float p1;
    vec3 Ambient; float p2;
    vec3 Diffuse; float p3;
    vec3 Specular;
    float Shininess;
    float Alpha;
};

// Fragment shader
layout(std140) uniform uniMaterial
{
    vec3 Emissive;
    vec3 Ambient;
    vec3 Diffuse;
    vec3 Specular;
    float Shininess;
    float Alpha;
};

```

Regards, Tobias

**My solution:**

```
struct GpuVec3
{
public:
    GpuVec3() {}

    GpuVec3& GpuVec3::operator=(const vec3& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = 1.0f;

        return *this;
    }

    GpuVec3& GpuVec3::operator=(const vec4& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = other.w;

        return *this;
    }

private:
    vec4 v;
};

typedef GpuVec3 GpuVec4;

```

# Answer
Tobias,

If you declare your vec3 class in C++ as having 16 byte alignment, you will have the matching offset.

```
struct vec3
{
float x,y,z;
} __attribute__ ((aligned(16)));

```

However this will align it everywhere. You might want a GPUVec3 which is aligned, and has copy constructor from your general vec3 so you don't burn that extra float everywhere.

I would, however, suggest stuffing your alpha into the w component of some of those vectors to improve bandwidth since you are just burning memory there. I wouldn't surprised that, in addition to losing a float per vector3, you are also losing 2 floats at the end of your uniform structure.

```
struct Material
{
public:
    vec4 EmissiveAndShineness;
    vec4 AmbientAndAlpha;
    vec3 Diffuse; float pad;
    vec3 Specular;
};

```

or

```
struct Material
{
public:
    GPUVec4 EmissiveAndShineness; // sizeof(GPUVec4) == 16
    GPUVec4 AmbientAndAlpha; // sizeof(GPUVec4) == 16
    GPUVec3 Diffuse; // sizeof(GPUVec3) == 16
    GPUVec3 Specular; // sizeof(GPUVec3) == 16
};

```
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Streamline Facebook and Google Play Game Services integration in Android Game
This has been confusing me a lot .

I am creating a simple 2D platformer which I wish to make social. So I thought of letting users do the following:

* Share their in game objective completion/ their high score etc with their friends.
* Challenge their friends to have a better score / better multiplier etc from their's
* View leaderboards of high score , most distance traveled etc both social and global.

So My First preference was Facebook , simply because people have better social connections there.

But then Google Play game services integration has another advantage, It makes you game available in their game services app and may be boost your game ranking in play store if you have game services integrated. But then I'' need to have leaderboards(same ones) for google plus as well. That 'll be too confusing for people.

I do not want people to sign in twice in my app. That'll simple cut down and disperse the number of people getting social with the game.

I personally want to use facebook alone but then google game services may be boosts my app in store.

Can someone tell me a solution to use them both frictionlessly and get the most out of them in my game

# Answer
> 1 votes
I was earlier in the same confusion and finally found out there is no proper solution for this. My consideration for Google play was not for ranking but for using the leaderboards and multiplayer features. And again If I go with Google Play Services alone, I miss a-lot with Facebook login.

So you decide which has more weightage and pick one of it. If you are targeting only for Android I suggest going alone for Google Play services as most of the users will have an account.

I picked Parse.com and implemented my own leaderboards and used Facebook for logging in (as I targeted iOS as well, I see FB has more reach).

In between, I tried OpenKit and dropped as its getting closed soon. Now i'm checking NextPeer which is a bit close enough to solve my problem. Will update once I play with NextPeer.

Hope this helps!

---
Tags: android, facebook, social, google-play-services
---


title: Making my character jump

text:
# Question
Title: Making my character jump
How do I fix my code?

At the moment my character goes up for as long as you hold the up key. I want a more jump like effect where the character will drop back down when it reaches a certain height. I want the character to only be able to jump again once it's fallen back down.

Below is my code so far.

```
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500, height = 400, speed = 4;

var score = 0;

var player = {
        x: 40,
        y: 350,
        width: 20,
        height: 20,
        gravity: 20,
        weight: 1
    };

window.addEventListener("keydown", function(e){
        keys[e.keyCode] = true;
    }, false);

window.addEventListener("keyup", function(e){
        delete keys[e.keyCode];
    }, false);

function game(){
    update();
    render();
}

function update(){
    if(keys[38]) player.y-=speed;

    if(speed < player.gravity) player.y+=player.weight;

    if(player.x < 0) player.x = 0;
    if(player.y < 0) player.y = 0;
    if(player.x >= width - player.width) player.x = width - player.width;
    if(player.y >= height - player.height) player.y = height - player.height;
}

function render(){
    context.clearRect(0,0,width,height);

    context.fillStyle = "blue";
    context.fillRect(player.x, player.y, player.width, player.height);

    setInterval(function(){
            game();
        }, 1000/60)
}

```

# Answer
You need to handle the player objects velocity vector i.e. it's speed **and direction**.
You also need gravity as a constant downward acting force.
Finally you also need to be able to detect if/when the object is standing on firm ground i.e. when they are able to jump (in this case it appears to be fairly straight forward matter of floor y = 0, i.e. if y==0 then object is on the floor, else it's in the air).

If the object is on the floor and the jump button is pressed, add the jump velocity vector, else, if it's in the air, add gravity vector.
On update move the object (barring any collisions) along it's velocity vector.

Trying to expand farther is proving to be beyond my writing abilities but there are countless excellent examples out there already for basic physics for games, for example
http://www.richardlord.net/presentations/physics-for-flash-games
> 1 votes

---
Tags: javascript
---


# Question
Title: Quaternion Rotation - Clockwise or Counter-Clockwise?
when we specify a Quaternion as `(axis of rotation, rotation amount)`, in which 'direction' is the rotation, assuming we are looking down the rotation axis (i.e. camera at the origin, looking along the axis vector)?

Does it depend on the handed-ness of the co-ordinate system?

Or is it actually a moot point / stupid question?

# Answer
It depends on the coordinate system you're working in.

In a **right-handed coordinate system** (eg. x right, y up, z points toward the viewer), the **right-hand rule** applies, as mklingen describes in the existing answer.

In a **left-handed coordinate system** (eg. x right, y up, z points away from the viewer), the **left-hand rule** applies - you point your left thumb along the rotation axis, and a positive rotation turns in the directions your fingers curl.

So it's important to know what coordinate system you're working with. Unity for instance uses a left-handed coordinate system. 3DS Max uses a right-handed coordinate system. Changing handedness flips the sign of an odd number of axes, and all rotation angles.

---

"Oh, so Quaternions are basically... 4D vectors, then? That we just give another name?"

Not quite. Like 4-vectors, they are 4-tuples of numbers, but interpreted such that three of the four components are measured in imaginary units. That means that two quaternions multiply together differently than they would if composed of real numbers (because 1i * 1i = -1). This weird multiplication means that they combine like 3D rotations do (something you don't get out-of-the-box with real numbers), which is why we often use them to describe rotations and orientations.
> 4 votes

# Answer
Quaternions are not axis/rotation vectors. That's just not how they work. They do *encode* an axis/rotation, but not in the way you describe. Check out the equation from wikipedia:

Given an axis \[a\_x, a\_y, a\_z\] and angle theta,

```
q = [a_x * sin(theta / 2), a_y * sin(theta / 2), a_z * sin(theta / 2), cos(theta / 2)]

```

That said, if you *do* have an axis/rotation vector, it follows the right hand rule. Looking down the axis of rotation, positive rotations will appear clockwise. Point your right thumb along the axis of rotation. The curl of your fingers is the angular motion of a positive rotation along that axis.
> 1 votes

---
Tags: rotation, quaternion
---


title: SharpDx Custom effect in SpriteBatch

text:
# Question
Title: SharpDx Custom effect in SpriteBatch
I'm trying to port a blur effect from an XNA project over to SharpDx, and I get a "Null Reference Exception" wich I'm unable to find the reason for.

```
    private void blurShadow(RenderTarget2D to, RenderTarget2D from, int dir)
    {
        _graphicsDevice.SetRenderTargets(to);
        _shadowBlurEffect.CurrentTechnique.Passes[dir].Apply();
        _spriteBatch.Begin(SpriteSortMode.Deferred, _shadowBlurEffect);
        _spriteBatch.Draw(from, Vector2.Zero, Color.White);
        _spriteBatch.End();  // <-- Null Reference Exception here
    }

    public void Draw()
    {
        _graphicsDevice.SetRenderTargets(_graphicsDevice.DepthStencilBuffer, ShadowDepthTarget);
        _graphicsDevice.Clear(Color.White); // Clear the render target to 1 (infinite depth)
        foreach (var obj in ShadowCastingObjects)
            obj.Draw(Camera, DrawingReason.ShadowDepthMap, this);

        blurShadow(_shadowBlurTarg, ShadowDepthTarget, 0);
        blurShadow(ShadowDepthTarget, _shadowBlurTarg, 1);

        _graphicsDevice.SetRenderTargets(_graphicsDevice.DepthStencilBuffer, _graphicsDevice.BackBuffer);
    }

```

The render targets are created like this:

```
    ShadowDepthTarget = RenderTarget2D.New(_graphicsDevice, width, height, PixelFormat.R16G16.Float);
    _shadowBlurTarg = RenderTarget2D.New(_graphicsDevice, width, height, PixelFormat.R16G16.Float);

```

This is the shader code, I have tried variuos versions of the method signatures - in vain:

```
Texture2D Texture;
SamplerState TextureSampler;

// Precalculated weights and offsets
float weights[15] = { 0.1061154, 0.1028506, 0.1028506, 0.09364651, 0.09364651,
    0.0801001, 0.0801001, 0.06436224, 0.06436224, 0.04858317, 0.04858317,
    0.03445063, 0.03445063, 0.02294906, 0.02294906 };

float offsets[15] = { 0, 0.00125, -0.00125, 0.002916667, -0.002916667,
    0.004583334, -0.004583334, 0.00625, -0.00625, 0.007916667, -0.007916667,
    0.009583334, -0.009583334, 0.01125, -0.01125 };

float4 BlurHorizontal(
    float2 UV : TEXCOORD0) : SV_Target
{
    float4 output = float4(0, 0, 0, 1);
    for (int i = 0; i < 15; i++)
        output += Texture.Sample(TextureSampler, UV + float2(offsets[i], 0)) * weights[i];
    return output;
}

float4 BlurVertical(
    float2 UV : TEXCOORD0) : SV_Target
{
    float4 output = float4(0, 0, 0, 1);
    for (int i = 0; i < 15; i++)
        output += Texture.Sample(TextureSampler, UV + float2(0, offsets[i])) * weights[i];
    return output;
}

technique Tech
{
    pass Horizontal
    {
        SetGeometryShader(0);
        SetVertexShader(0);
        SetPixelShader(CompileShader(ps_4_0, BlurHorizontal()));
    }

    pass Verical
    {
        SetGeometryShader(0);
        SetVertexShader(0);
        SetPixelShader(CompileShader(ps_4_0, BlurVertical()));
    }
}

```

# Answer
It turns out that an effect passed to SpriteBatch.Begin must follow specific conventions:

```
Texture2D<float4> Texture : register(t0);

// SpriteBatch expects that default texture sampler parameter will have name 'TextureSampler'
sampler TextureSampler : register(s0);

// SpriteBatch expects that default vertex transform parameter will have name 'MatrixTransform'
row_major float4x4 MatrixTransform;

void VSMain(
    inout float4 color    : COLOR0,
    inout float2 texCoord : TEXCOORD0,
    inout float4 position : SV_Position)
{
    position = mul(position, MatrixTransform);
}

// Precalculated weights and offsets
float weights[15] = { 0.1061154, 0.1028506, 0.1028506, 0.09364651, 0.09364651,
    0.0801001, 0.0801001, 0.06436224, 0.06436224, 0.04858317, 0.04858317,
    0.03445063, 0.03445063, 0.02294906, 0.02294906 };

float offsets[15] = { 0, 0.00125, -0.00125, 0.002916667, -0.002916667,
    0.004583334, -0.004583334, 0.00625, -0.00625, 0.007916667, -0.007916667,
    0.009583334, -0.009583334, 0.01125, -0.01125 };

// Blurs the input image horizontally
float4 PSBlurHorizontal(
    float4 color: COLOR,
    float2 UV : TEXCOORD0) : SV_Target
{
    float4 output = float4(0, 0, 0, 1);
    for (int i = 0; i < 15; i++)
        output += Texture.Sample(TextureSampler, UV + float2(offsets[i], 0)) * weights[i];
    return output * color;
}

// Blurs the input image vertically
float4 PSBlurVertical(
    float4 color: COLOR,
    float2 UV : TEXCOORD0) : SV_Target
{
    float4 output = float4(0, 0, 0, 1);
    for (int i = 0; i < 15; i++)
        output += Texture.Sample(TextureSampler, UV + float2(0, offsets[i])) * weights[i];
    return output * color;
}

technique Tech
{
    pass Horizontal
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_4_0, VSMain()));
        SetPixelShader(CompileShader(ps_4_0, PSBlurHorizontal()));
    }

    pass Verical
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_4_0, VSMain()));
        SetPixelShader(CompileShader(ps_4_0, PSBlurVertical()));
    }
}

```
> 1 votes

---
Tags: hlsl, sharpdx, spritebatch
---


# Question
Title: Predicting circle-circle bounce vector when aiming one at another
I am making a game with libGDX (with box2d) in which you drag and aim one circle body at another then release to fire. I would like to be able to predict the path of the second circle based on the aim of the first. very like 8 ball pool when aiming your shot.

I have been playing around with various trig solutions but i just cant get it to work at all! I have also been reading about ray casting in which I would cast a ray from the center of the first circle body in the direction i am aiming. this would tell me where the ray intersects the second circle body (if it does so) but it would not be correct as the circle fixture would not actually collide where they ray does because it obviously has a radius.

Is the trig solution the correct path or is there a simpler way to do this?

# Answer
The easiest solution I found was to attach a sensor with a radius the sum of the two radii to the second circle and a RayCast callback returning the fraction and filter for just sensors. The collision point is where the center of the first circle will be upon contact. a vector between the contact point and the center of circle two gave me the predicted path of the circle.
> 0 votes

---
Tags: java, libgdx, trigonometry
---


# Question
Title: Implementing a camera / viewport to a 2D game
What is the most practical way to implement camera/viewport to a 2D-game?

I've read, that I should store the object *world position* instead of position relative to the screen?

**Current situation:**

I have implemented a simple 2D-game where I load objects and levels from XML-files. Currently the level XML-file looks like this:

```
<map>
   <tile obj="ground" x="0" y="555" />
   <tile obj="ground" x="16" y="555" />
   <tile obj="ground" x="32" y="555" />
   ...
</map>

```

All objects have a 2d-vector "position" storing their current location on the screen.

**What I want it to be:**

In the picture:

* Camera is either 800x600 or 640x480
* Blocks and sprites are 16x16 pixels.
* World size may vary
* The coordinates probably should be normalized relative to the world, not to the screen?
* Viewport position relative to player's x, y and moves when the player reaches camera dead zone (similar to this video).

I'm asking pseudo examples / articles, but if you need to know what I'm using for the development: SDL & C/C++.

# Answer
You need to have every object positioned relative to the world instead of the screen. Your camera should also have its own world coordinates so it can be drawn at a relative position in the world. It may also be convenient to have your camera follow an object, so wherever the object is, the camera just uses its coordinates. Typically the camera's coordinates will position it from the upper left corner. This means the camera would have a world position of approximately (0,24) in the picture.

As for actually drawing the objects the camera can "see", you must draw all objects relative to the camera's world coordinates. To compute an object's screen position relative to the camera, simply do:

```
int screenX, screenY; //screen position of the object being drawn

screenX = object.x-camera.x;
screenY = object.y-camera.y;

```

Obviously some objects are not actually visible to the camera, so you may want to implement a view culling system.
> 20 votes

# Answer
It's best to do all of this in the GPU using the World and View matrices, **not** by modifying where you draw the objects on the CPU.

That way, you can change the camera arbitrarily (even zoom it in and out!) and it will just magically work. You can still do view culling as well to save on draw time. And none of your code for drawing the world will have to change after you've setup the view and world matrices correctly.

In SDL, you can probably just inline OpenGL calls such as `glOrtho` and `glTranslate`.

See this thread.
> 2 votes

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


title: Bridge made out of blocks at an angle

text:
# Question
Title: Bridge made out of blocks at an angle
I want the player to select 2 points (vectors). With these 2 points a floor should be created. When these points are parallel to the x-axis it's easy, just calculate the amount of blocks needed by a simple division, loop through that amount (in x and y) and keep increasing the coordinate by the size of that block.

The trouble starts when the 2 vectors aren't parallel to an axis, for example at an angle of 45 degrees. The 2 red dots would be the player selected locations. (The blocks indeed aren't square.) .

How do I handle the math behind this?

# Answer
In 2D:

The position of each block placed is `{sin(theta),cos(theta)} = {x,y}`. Hence at `theta = 90°`, the position will move only in the x-axis, by one block each time. The rotation of each block should be the same `theta` as well.
> 1 votes

# Answer
You could also achieve this in a "dumb" cycle, it is not optimal but will work. Simply keep adding any block next to the current that is inside the area. Lets say you would like a list of the blocks:

```
Rectangle area = new Rectangle(A.x, Math.Max(B.y,B.x), A.y, Math.Min(B.y,B.x));
List<Block> blocks = new List<Block>();
Queue<Block> blockQueue = new Queue<Block>();
Block currentBlock = new Block(Point A, //...the first block corrdinates
//rest vertices depends on data you didnt supply (rotation, block size etc. you can calculate that)
blocks.Add(currentBlock );
blockQueue.Enqeue(currentBlock);

while(!blockQueue.isEmpty)
{
    currentBlock = blockQueue.Deqeue();
    foreach(Block b in currentBlock.Neighbours)// any neighbour block, if zou dont have them, generete them
    {
        if(isInsideRect(b))// valid block?
        {
            blockQueue.Enqeue(b);
            blocks.Add(currentBlock);
        }
    }
}

//check if inside wanted area
bool isInsideRect(b)
{
    foreach(Point p in b.Vertices)
        if ((p.x < area.Right && p.x > area.Left) && (p.y < area.Top && p.y > area.Bottom))
            return true;
    return false;
}

```
> 0 votes

# Answer
## Overview

So the algorithm is a simple fill algorithm that first finds the number of blocks needed to adequately cover the diagonal. Then it walks along this diagonal is block long increments. At each increment the fill algorithm branches out at both right angles and adds blocks so long as the center is within the box.

Also just walked though this with a few pen and paper examples so might take some refining.

The diagonal walking bit.

## The Algorithm

Input and computing a few bit of basic info

```
List BoxCenterList

BlockWidth
BlockLength

DiagonalLength = (TR - BL).lenght()
DiagonalDirection = (TR - BL).Normalize()
DiagonalDirectionRightAngle = new Vector2(-DiagonalDirection.Y, DiagonalDirection.X)

Center = (TR + BL) / 2

```

First we find the center, and then calculate the number of blocks needed to adequately cover the diagonal.

```
BlocksAlongDiagonal = Math.Ceiling(DiagonalLength / BlockLenght) //Number of blocks along diagonal
BlockDiagonal = BlocksAlongDiagonal * BlockLenght //Length of the bridge along the diagonal

```

For filling the blocks in we start in the bottom left corner along the diagonal such that the walking point is in the center of where the block should be.

```
StartPoint = Center - ((DiagonalDirection * BlockDiagonal) / 2)
StartPoint += BlockLenght / 2

```

And then we begin walking up the diagonal.

```
for (i in Range(BlockLenght))
    BoxCenterList.Add(StartPoint)

```

Branch out at a 90 degree angle and add boxes so long as the center is in the box

```
    TravelVector = StartPoint + (DiagonalDirection * BlockWidth)
    while(rectangle.contains(TravelVector))
        BoxCenterList.Add(TravelVector)
        TravelVector += (DiagonalDirection * BlockWidth)

```

Branch out at the other 90 degree angle and add boxes so long as the center is in the box

```
    TravelVector = StartPoint + (-DiagonalDirection * BlockWidth)
    while(rectangle.contains(TravelVector))
        BoxCenterList.Add(TravelVector)
        TravelVector += (-DiagonalDirection * BlockWidth)

    StartPoint =+ DiagonalDirection * BlockLenght

```

To use the algorithm simply take the `BoxCenterList` and add a box at each location rotated to align with the `DiagonalDirection` vector. If you want to guarantee the entire box is covered change the condition from "is the center in the box" to "is a corner in the box"
> 0 votes

# Answer
You said it was easy when the two vectors were aligned to the X-axis. So, first align them to the X axis, and your problem is solved! The only difficulty will be finding out whether the blocks are inside a rotated bounding box (assuming that you wanted the blocks to cover the bounding box only).

```
Vector point1;
Vector point2;

// First, create an orthonormal coordinate system. Origin is point1.
Vector xAxis = (point2 - point1);
float dist = xAxis.length();
xAxis /= dist;
Vector yAxis = xAxis.cross(0, 0, 1);
yAxis.normalize();

// You will need to compute these first
int blockWidth, blockHeight;
BoundingBox bounds;

// Diagonal of the bounding box
float squareDiagonal;

// Iterate along the vector from point1 to point2
for (float x = 0; x < dist; x+= blockSize)
{
   // Iterate over the vector from the lower right corner to the upper left
   for (float y = -squareDiagonal * 0.5; y < squareDiagonal * 0.5; y +=blockHeight)
   {
       Vector blockPos = x * xAxis + y * yAxis + point1;

       // You will need to implement a function that intersects the bounds with a rotated block at the given position.
       if (bounds.ContainsBlock(blockPos)
       {
          // You will need to make sure this rounds properly.
          CreateBlock(blockPos);
       }
   }
}

```
> 0 votes

---
Tags: mathematics, angles
---