# Question
Title: unity - problem in limiting rotation of object?
I am trying to make a game with unity.

In this game, player uses mouse to rotate a container or box around x and z (rotate to left and right and also toward the camera and opposite).

I used below code to control movement and limit it.

```
float zRot = transform.eulerAngles.z;
float xRot = transform.eulerAngles.x;
float yRot = transform.eulerAngles.y;
Debug.Log (
  "xDir : "  + xRot.ToString() +
  " yDir : " + yRot.ToString() +
  " zDir : " + zRot.ToString() );

if ((xRot >= 330 || xRot <= 30) && (zRot >= 330 || zRot <= 30)) {
  transform.Rotate (Input.GetAxis ("Mouse Y"), 0, -Input.GetAxis ("Mouse X"));
}
else {
  Debug.Log(xRot.ToString() + "  " + zRot.ToString ());

  transform.Rotate (-transform.rotation.x , transform.rotation.y,-transform.rotation.z );
}

```

The contatiner rotate 60 degrees in x and z and when it gets to the limits it stops, which is what I want. However when I rotate in both direction to the near the limits (330 or 30), the contatiner becomes out of control and it rotates freely and constantly. It's like the contatiner has passed the limits.

The questions are:

* Did I used a good approach to limit the rotation and how to stop the object completely when it get to the limit of rotation?
* When and why the object becomes out of control exactly?

# Answer
> 2 votes
The issue with using transform.Rotate() is you're cumulating rotations; once the object is rotated on one axis, the other axis then rotates it at an angle which isn't the original intended axis.

It's kinda hard to explain but try this:

* Take a dice,
* rotate it forward 90 degrees,
* then right 90 degrees,
* then backward 90 degrees,
* then left 90 degrees

and it's **NOT** back to the same orientation. For more info see Gimbal lock, there are a lot of issues using Euler angles for doing rotations.

Instead I would use the Transform.LookAt(Vector3 pos, Vector3 Up) or Quaternion.LookRotation function:

```
float limit_x = 1;
float limit_y = 1;
float mouse_scale = ???; // figure this one out through experimentation

y += Input.GetAxis ("Mouse Y") * mouse_scale;
x += -Input.GetAxis ("Mouse X") * mouse_scale;

x = Mathf.Clamp(x, -limit_x, limit_x);
y = Mathf.Clamp(y, -limit_y, limit_y);

transform.rotation = Quaternion.LookRotation(Vector3.forward + new Vector3(0, x, 0), Vector3.up + new Vector3(y, 0, 0));

```

What this does is create a rotation where the object's Z axis points at the first parameter (a direction), and the object's Y axis to the second parameter (also a direction, what is "up" for the object). (The X axis automatically point at 90 degrees to both Y and Z.)

We're passing the Z direction as (0, 0, 1) + (0, x, 0) so we're changing "forward" to point slightly up or down.

We're passing the Y direction as (0, 1, 0) + (y, 0, 0) so we're changing "up" to point slightly left or right.

This trick is non-linear and you cannot rotate completely around (in this case I'm limiting to 45 degrees both axis) but for a tilt-box this has worked well enough for me.

If you need proper linear rotation use:

```
transform.rotation = Quaternion.AngleAxis(x, Vector3.z) * Quaternion.AngleAxis(y, Vector3.x);

```

`y` and `x` are in degrees with this so `limit_x` and `limit_y` should be adjusted accordingly (e.g. 45)

Depending on how your world & object are oriented you might need to change the angles of rotation.

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


# Question
Title: Modifying alpha of pixels in sufrace/texture
I have a texture who's surface I've loaded with an image. Some areas of this image are completely transparent (alpha = 0), some completely opaque, and some are somewhere in the middle.

The issue I'm having is that when i draw the texture, the semi-transparent areas are "too" transparent. I want to make them more opaque.

In short, i want to multiply the alpha of all pixels on the surface by some constant. 0's will stay at zero. 255 will stay at 255. But the semi-transparent should get more opaque.

Is this possible? I've been messing around with the alpha blending render states but none of them seem to be able to do what i need them to do.

Thanks!

# Answer
One easy way is to square-root the alpha.

```
Sqrt(0) -> 0; // stays transparent
Sqrt(1) -> 1; // stays opaque

// anything between becomes more opaque
Sqrt(0.125) -> 0.353553391;
Sqrt(0.25) -> 0.5;
Sqrt(0.5) -> 0.707106781;

```

You'll have to pre-process your texture or do it in the pixel shader.

`pow(alpha, y)` is another easy way to do it, `pow(alpha, 0.5)` is a square root, `pow(alpha, 0.3333333333333333)` is a cubic root, etc. Play with values of y above 0 and below 1.
> 1 votes

---
Tags: directx, directx9
---


# Question
Title: List of Lists for sending paths from client to server?
I have a client server scenario and I'm looking into distributed AI. I want the server to move x amount of ai characters around a map by pathfinding and then send the x amount of paths to the client which will apply each path to its corresponding AI character. This is for research purposes to see if this approach, by sending the new path of each server AI to the client AI for it to follow, is better than constantly sending a positional update across a network everytime a server gameobject moves slightly. I would like this X amount to range anywhere from 10 to 2000, a big ask i know, but i'll go into what I have atm.

Atm I have this working for 2 AI characters and it can be expanded, but with my existing code it would mean an awful lot of copying and pasting! So on the server when the path is created it is sent to a script which can bundle it into an RPC an send it on its way:

```
public class GrabbingArrayFromUnitScript : NetworkBehaviour {

public List<Vector3> receivedArrays = new List<Vector3>();
public List<Vector3> receivedArrays1 = new List<Vector3>();

    [ClientRpc]
    void RpcPosFromServerToGoTo(Vector3 [] path, String name)
    {

    if (name == "SeekerPrefab")
    {
        receivedArrays.AddRange (path);
        UnityEngine.Debug.Log ("Received");
    }
    if (name == "SeekerPrefab (1)")
    {
        receivedArrays1.AddRange (path);
        UnityEngine.Debug.Log ("Received 1");
    }

    }

public void PrintPath(Vector3 [] path)
{
    if (isServer)
    {
        UnityEngine.Debug.Log("Send Array ...");
        RpcPosFromServerToGoTo (path, transform.name);
        UnityEngine.Debug.Log("Sent!!");

    }
}

}

```

So as you can see from the above if I wanted to add more AI characters in I would have to add more if statements to the RPC call, and if I wanted 2000 AI in that would be alot of copying. So what could I do here to reduce this code down? Would I use a list of lists? Any help would be greatly appreciated!

# Answer
> 0 votes
Below is what I have managed to throw together, time is of the essence and tbh dictionaries confuse me, they are probs more efficient, but this will do for now:

```
public class AiManager : NetworkBehaviour {

ClientAiMoveToPosArray clientAiMoveToPosArray;

[ClientRpc]
void RpcPosFromServerToGoTo(Vector3 [] path, String name)
{

    clientAiMoveToPosArray = GameObject.Find (name).GetComponent<ClientAiMoveToPosArray> ();
    clientAiMoveToPosArray.receivedArrays.AddRange(path);

}

public void PrintPath(Vector3 [] path, String name)
{
    if (isServer)
    {
        UnityEngine.Debug.Log("Send Array ..." + name);
        RpcPosFromServerToGoTo (path, name);
        UnityEngine.Debug.Log("Sent!!");

    }
}
}

```

Whenever I send the path to the RPC I also send the name, then when sending the RPC the name goes aswell. Reading in the RPC the object is tracked down by its name and then the script which reads the path is brought up and the path placed into it. Again I have been rushed for time. I will try a dictionary at a later time.

# Answer
> 1 votes
Use a dictionary to keep the entities and requests in them, and a SearchContext to hold the related data for one entity together:

```
class SearchContext
{
  List<Vector3> points;
};

public Dictionary<String, SearchContext> context = new Dictionary<String, SearchContext>();

[ClientRpc]
void RpcPosFromServerToGoTo(Vector3 [] path, String name)
{
    SearchContext context;
    // context doesn't exist yet - add it
    if ( contexts.TryGet( name, out context ) == false )
{
   context = new SearchContext;
   contexts[ name ] = context;
}

context.points.AddRange( path );
UnityEngine.Debug.Log ("Received");
}

```

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


title: Trailing dots effect

text:
# Question
Title: Trailing dots effect
I am making a "Don't touch the spikes" remake in unity C#. I want to make the effect of the dots behind the bird like in the image below. How can I do this?

# Answer
Unity has a readily available Trail Renderer. That's all you need. The Trail Renderer is used to make trails behind objects in the scene as they move about. From the source:

> The Trail Renderer is great for a trail behind a projectile, or contrails from the tip of a plane’s wings. It is good when trying to add a general feeling of speed.
>
> When using a Trail Renderer, no other renderers on the GameObject are used. It is best to create an empty GameObject, and attach a Trail Renderer as the only renderer. You can then parent the Trail Renderer to whatever object you would like it to follow.

In other words, it is best to create a child object and add TrailRenderer component to it instead of adding directly to the main game object.
> 1 votes

# Answer
You will need to create a particle prefab with the small circles as the image that get more transparent and smaller as they travel away. There's quite a lot more to it than that but to go into I feel would take an extremely long answer. Maybe when I get home and can take screenshots but there are a lot of tutorials on the particle system that would probably do a better job than me
> 0 votes

---
Tags: unity
---


# Question
Title: Oculus Integration on Unity 5.1.2 not showing Oculus Lenses (like two black boxes) when debugging/editor
I added Oculus Utilities for Unity 5.1.2, created a simple scene, added OVRCharacterController prefab, it works fine like normal fps controller but as far as I know, it should show something like 2 separate display screen on monitor with that black distortion outline frame. I have no hmd. The runtime is running, and OVR service is also running. It is set to extended mode. One thing to note here is that there is no Oculus setting option in player settings.

# Answer
I found out that this is the way it work in Unity5 and above so there was nothing to worry about.
> 0 votes

---
Tags: unity, oculus
---


# Question
Title: How do I make sprites overlap eachother based on a layering system?
In Unity, I am building a 2D puzzle game, however I need to make sure that certain sprites are rendered on top of other sprites when they are above them.

Here is an example switch (left) and block (right).

I wanted to make sure that the green block appears on top of the green switch when it passes over it, so how do I avoid a situation like this happening?

# Answer
SpriteRenderer has Order in layer inspector property which determines sprite draw order.

You can see how to use it in this tutorial video: https://unity3d.com/learn/tutorials/modules/beginner/2d/sorting-layers
> 4 votes

# Answer
The selected answer does the job. If you want to organize the pieces that a certain kind appear on top of another kind, and you have a lot of pieces, take a look at Sorting Layers. If not, you learnt something new ;)
> 0 votes

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


title: How to test for adjacency?

text:
# Question
Title: How to test for adjacency?
I need to come up with a better way to test for adjacency in a grid environment. Imagine that the blue is water, the green is land, and the red dot is a character. What I need to do is ***efficiently*** return a list of Vector positions of all grid tiles for the "island" that the character is on.

I have attempted to do this with raycasts using the following procedure.

-raycast at all of the immediately adjacent nodes surrounding the player.

-if (hit == land) then add hit to adjacent list.

-raycast at all immediately adjacent grid cells around each of the previous hits on land. (if they have not already been tested)

-if (hit == land) add to the adjacent list.

-loop until no more hits on land.

this seems to work okay, but is not very fast. If possible I need to maintain the raycasting because the levels are randomly generated at run time.

# Answer
It's called a flood fill, and it's what you see in paint programs. It's very fast. Pseudocode:

```
declare visited list //the results you want
declare unvisited list

add current element (where red dot is) to unvisited list

while unvisited list not empty
   get current element from unvisited list
   add current element to visited list
   for all (8) neighbours of current element
       if neighbour is green
          if neighbour is not in visited list //be sure not to process same ones again!
              add neighbour to unvisited list
   remove current element from unvisited list

```

The way I'd do this is using a set (or hashtable if set not available); as these structures don't allow duplicates, you don't have to do the `if neighbour is not in visited list` in your own code.
> 5 votes

# Answer
so let me understand, you have a grid based datastructure and you use raycasting to analyse the data in it?

If so, what you should use is simple a recursive search. IF you make iterative will be even faster.

Simply start from the tile where your character is and then test the adjacent ones using indices. If they are island, repeat the operation until you don't find any.

Look for Breadth Search on Grids for further information. It's more or less like you described, but you don't really need the raycast.
> 1 votes

# Answer
If your land is fixed and predetermined when your game starts, you could store all information on adjacent tiles for each tile in a vector (or better a vector of vector, such as in C++, `std::vector<std::vector <int> >` **during the game initialization stage** and before your actual gameplay starts. The elements in the list contains information on all adjacent land tiles (e.g. for your 46th tile, the adjacent are 45, 47 etc.) Hence, you don't have to check the same thing over and over again in your gameloop.

Secondly, store the size of each vector too in a vector for each tile during your initialization. Thus don't have to check how many there are adjacent tiles for each tile (e.g. by size()) within your gameloop when you iterate over your adjacent tiles, for example if you want to show where your characters can move to.
> 1 votes

---
Tags: unity, c#, raycasting, grid, logic
---


title: Position UI.Button to mouse position

text:
# Question
Title: Position UI.Button to mouse position
This has been discussed a couple of times, but I didn't find any solution:

I want to set the position of an UI.Button to my mouse position. I can get the mouse position like this:

```
Vector3 cameraVector = Camera.main.ScreenToWorldPoint(Input.mousePosition);

```

Problem: The UI elements are using another "coordination system". How can I handle that problem?

# Answer
> 3 votes
Input.mousePosition is already in screen coordinates. You do not need any transfomations, just pass it to RectTransform.anchoredPosition.

Here is example of doing it: http://answers.unity3d.com/questions/781643/unity-46-beta-rect-transform-position-new-ui-syste.html

# Answer
> 2 votes
You probably want to use Unity's `RectTransformUtility` with a call to the `ScreenPointToLocalPointInRectangle`. Or `ScreenPointToWorldPointInRectangle` if you have a World Space UI. Then set the UI `anchoredPosition`.

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


# Question
Title: Generating Weapon Damage Based on Item Level
I bring with me a question on loot generation from ARPGs. In Diablo 3, items are generated for each level range, with damage range being defined manually.

I need help with an equation that generates weapons with damage scaling up based on level.

Level 1 - LowD - Lowest Damage

Level 80 - CapD - Cap Damage

I would like to generate weapons that scale linearly in damage based on item level. So item level is an important variable.

There are two additional factors: min damage and max damage.

Damage Range Example Level X Sword: MinDmg - MaxDmg

MinDmg is a random number rolled by dice based on the linear scale with level. MaxDmg likewise, is a random number rolled by dice based on the linear scale with level.

Level 1 Sword: 1-3

Level 10 Sword: 10-15

Level 10 Sword: 9-14

Level 80 Sword: 250-300

CapD is there to set the ceiling that the maximum range can reach up to. Example is the max damage a level 80 sword can deal.

# Answer
> 7 votes
I would not define minDamage and maxDamage when generating the item at all. Your goal is to find minD and maxD, but it is important to realize that there is *single* damage number(in your case, as you said its linear scaling with level).
You know the damage is linear: `damage = scaling_factor * item_level`. For example scaling factor of sword might be 2, for dagger 1.5 and for two-handed axe it is 3. Also note I used `item_level`, if you want to have different quality items it might be a good idea to separate required level and item level(but you probably do that already).
The level 50 sword now has 100 damage, to introduce minD and maxD you should also define "randomness", lets call it `random_factor` and set it for all swords to 0.15 (=15%). Now you can get minD and maxD very easily:

```
minD = (1 - random_factor) * damage
maxD = (1 + random_factor) * damage

```

Every level 50 sword now has 85 to 115 damage. To improve randomness we will say random factor not same for all swords, but rather within some specific range, lets say from `min_rndF = 0.07` to `max_rnd_f = 0.24`.

```
rnd_f = rand(min_rndF, max_rnd_f)
var sword = new Sword(level, rnd_f)

```

At this point you are at the solution you wanted, level 50 sword can be anywhere between `93-107` and `76-124` swords, all of these having exactly same DPS.
If you want to play with the randomness even further, you might say you dont want to have all the possibilities from above equally likely and for example want the more unbalanced versions(93-107 and 76-124) less likely so that the player would find "average" 85-115 swords more often. In that case you should also choose the distribution.
As I mentioned above, you can also separate the required(displayed) level and the actual level so player can find slightly worse or slightly better swords of same level, that can be achieved in similar manner:

```
rnd_f = rand(min_rndF, max_rnd_f)
rnd_l = rand(-quality_rnd/*0.1*/, quality_rnd)
var actual_level = (1 + rnd_l) * level
var sword = new Sword(level, actual_level , rnd_f)

```

This way, level 50 swords can be anywhere between `84-96`(low quality, low randomness), `68-111`(lq, hr), `84-138`(hq, hr) or `103-119`(hq, lr), all equally likely. Or even all not equally likely(if you chose to use non-default distribution).

# Answer
> 2 votes
One way to achieve it is to find a formula for the maximum damage, and one for the minimum damage, both based on the level, then find random values in-between these.

Start by devising 2 formulas:

```
maxLv       = 80
maxAtLvOne  = 3
maxAtLvMax  = 300
minAtLvOne  = 1
minAtLvMax  = 250

maxAtLv( inLv )
  return inLv * ((maxAtLvMax - maxAtLvOne) / maxLv) + maxAtLvOne

minAtLv( inLv )
  return inLv * ((minAtLvMax - minAtLvOne) / minLv) + minAtLvOne

```

This will give you the minimums and maximums at each level.

Then you can generate your values for your weapon:

```
genMinMaxAtLv( inLv, outMin, outMax )
  min = minAtLv( x )
  max = maxAtLv( x )

  diff = max - min
  halfDiff = diff / 2

  outMin = min + rnd( 0, halfDiff )
  outMax = max - rnd( 0, halfDiff )

```

This offers the possibility to set the maximum and the minimum, and allows for generating random numbers in between.

In addition, you could also devise a 3rd and a 4th formula to replace the use of the `halfDiff` value used above: one for the variation of the maximum, and one for the variation of the minimum (you could also use only one for the two purposes, if it suits your needs). This furthers the control you can have on the data produced. (You could also transform this to a "minimal higher value" and a "maximal lower value".)

The graph has been made with this tool and this *Load & Save* string:

```
a0=2&a1=x*((300-3)/80)+3&a2=x*((250-1)/80)+1&a3=&a4=1&a5=4&a6=8&a7=1&a8=1&a9=1&b0=500&b1=500&b2=-0&b3=80&b4=0&b5=300&b6=10&b7=10&b8=5&b9=5&c0=3&c1=0&c2=1&c3=1&c4=1&c5=1&c6=1&c7=0&c8=0&c9=0&d0=1&d1=20&d2=20&d3=0&d4=&d5=&d6=&d7=&d8=&d9=&e0=&e1=&e2=&e3=&e4=14&e5=14&e6=13&e7=12&e8=0&e9=0&f0=0&f1=1&f2=1&f3=0&f4=0&f5=&f6=&f7=&f8=&f9=&g0=&g1=1&g2=1&g3=0&g4=0&g5=0&g6=Y&g7=ffffff&g8=a0b0c0&g9=6080a0&h0=1&z).

```

# Answer
> 1 votes
I recommend you to put a random valve between 1-4 depending on the type of the weapon.

That valve will mark the breach between the low and max attack valve. For example, if the valve is 1, make a rand between 5 and 10; 2 between 8 and 15...

That way depending on the type of the weapon and the valve that you have assign to them, the weapon will have a variable range of damage (for example a dagger) or less (an battle axe).

To set the base damage depending on the item lvl, you can multiply the item lvl by a base damage using the valve said before (different type of weapons can be more or less powerful in that case). For example, a dagger (wepon type 1) can have a base valve of damage 8, so you multiply the lvl by the base damage, and then using the rand function over the base damage that I have said before, to set the minimum and maximum number.

Example:

```
if(weaponType == 1){
   diference = rand(5, 10)
   damage = itemLvl * 8     //Being 8 the base damage for the weapon Type 1
}

minDamage = damage - diference/2
maxDamage = damage - diference/2

```

# Answer
> 0 votes
I've had a crack at something that might satisfy your needs (pseudo code below)

```
rand = new rand(level/2) -- 0 to level/2
min = level + rand
max = min + (level/2)

```

For example this will give you the following for some example levels:

Level 2: (rand = 1) min = 3 max = 4

Level 10: (rand = 4) min = 14 max = 18

Level 10: (rand = 1) min = 11 max = 12

Level 80: (rand = 35) min = 115 max = 150

If this doesn't meet your needs i can work up another solution

---
Tags: rpg
---


title: Unity 5: Stays slow after code runs

text:
# Question
Title: Unity 5: Stays slow after code runs
Hi guys :) I have just tweaked the FPSController Script so that when you are below 6y, you are slower and gravity is a little weaker. This is to simulate underwater effects, but when you come out of the water, the effects are still applied.

Code:

```
if ((transform.position.y < waterLevel) != isUnderwater) {
    isUnderwater = transform.position.y < waterLevel;
    m_WalkSpeed = 3;
    m_RunSpeed = 6;
    m_JumpSpeed = 12;
}

```

This is run in the `void Update()` void so that it checks for it every frame.

Does someone have a solution so when you come out of the water, the original movement is used? Thanks.

EDIT: Some people have been getting confused, so I'll explain. I'm running this `if(){}` statement in `public class FirstPersonController : MonoBehaviour`. I did not make my own class, I used their `void Update()` instead of making my own. So, any variables in that class cannot be used outside.

# Answer
Basically, you want to store the variables before changing them. And you change them only when the state change, i.e. when you go from over the water to under the water, and from under the water to over the water. You'll probably want to set these values from the editor. You can add the values for the underwater movement variables as class variables:

Add to the class `public class FirstPersonController : MonoBehaviour`:

```
// My Mod start
[SerializeField] private float m_waterLevel;

[SerializeField] private float m_underWaterWalkSpeed;
[SerializeField] private float m_underWaterRunSpeed ;
[SerializeField] private float m_underWaterJumpSpeed;

private float m_initialWalkSpeed;
private float m_initialRunSpeed;
private float m_initialJumpSpeed;

private bool m_isUnderwater;
// My Mod end

```

Add to the method `private void Update()`:

```
// My Mod start
if ((transform.position.y < m_waterLevel) && !m_isUnderwater) {
  // Switch state -> going from over the water to under the water

  // store the variables
  m_initialWalkSpeed  = m_WalkSpeed;
  m_initialRunSpeed   = m_RunSpeed ;
  m_initialJumpSpeed  = m_JumpSpeed;

  // update the state
  m_isUnderwater = true;
  m_WalkSpeed = m_underWaterWalkSpeed;
  m_RunSpeed  = m_underWaterRunSpeed ;
  m_JumpSpeed = m_underWaterJumpSpeed;
}
else if ( m_isUnderwater && transform.position.y > m_waterLevel ){
  // Switch state -> going from under the water to over the water

  // update the state: reset the variables
  m_isUnderwater = false;
  m_WalkSpeed = m_initialWalkSpeed;
  m_RunSpeed  = m_initialRunSpeed ;
  m_JumpSpeed = m_initialJumpSpeed;
}
// My Mod end

```

Add at the end of the method `private void Start()`:

```
// My Mod start
if ( transform.position.y < m_waterLevel ) {
  // store the variables
  m_initialWalkSpeed  = m_WalkSpeed;
  m_initialRunSpeed   = m_RunSpeed ;
  m_initialJumpSpeed  = m_JumpSpeed;

  // update the state
  m_isUnderwater = true;
  m_WalkSpeed = m_underWaterWalkSpeed;
  m_RunSpeed  = m_underWaterRunSpeed ;
  m_JumpSpeed = m_underWaterJumpSpeed;
}
else {
  m_isUnderwater = false;
}
// My Mod end

```
> 3 votes

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


# Question
Title: Is there an efficient way to identify in which run-time generated room a character is, in a non-grid 3D environment? How?
Here is what I am trying to implement. I wrote a script that allows the player to place walls during run-time, in non grid-based 3D environment (walls can be diagonal with rotation increasing/decreasing in amounts of 10 degrees). Like the figure below shows, since wall can form different angles, rooms might end up having both convex and concave angles:

What I have been looking for, without success so far, is a way to detect in which room a given character is, according to its position. Of course, if that was a grid-based setting, I could only pass an ID for each cell and then retrieve the ID of the cell where the given character stands. However, that being a non-grid setting and with irregular rooms that have shapes unknown in advance, how could I accomplish that in an efficient way?

Many thanks.

EDIT: Although it is a 3D environment, the problem may be treated as a 2D one since height is not a concern here.

# Answer
I think the easiest thing would be to solve it as a 2 dimensional problem. Further, if the constraints are such that each room must be 'closed' then it turns into a point-in-polygon problem, which is easy to solve - essentially a test is performed whereby a segment from the point to some infinite distance is tested against each segment of the polygon. If the number of times the ray crosses segments is odd, the point is inside the polygon. If it is even, the point is outside the polygon. There's already an answer here: https://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test

As noted by Wondra's comment & answer, it may be more bullet proof to use the signed winding number method instead, which handles self intersecting polygons and polygons with whole inside them. There is a C++ implementation is found here: http://geomalgorithms.com/a03-\_inclusion.html

You just need to track the polygon's vertices as the room is created for this to work.

The other thing you'll want to do is to take each room's minimum and maximum points to create an axis aligned bounding box. Prior to testing a room's polygon, test if the player's point is inside the bounding box. If it is not, then there is no point doing further tests for that room. Point-in-AABB 2D is very fast - check if Point.x is \>= AABB.min.x and Point.X \<= AABB.max.x, and the same for point.Y. This will greatly increase the performance of your search.

Finally, if you have a *lot* of rooms, you will want to organize your AABBs into a spatial structure to speed that up even more - either a grid, quad-tree or balanced AABB tree (look at Box2D's broadphase for this one - dynamic bounding volume).

As Loren Pechtel outlined in his comment, the grid would store a linked list in each cell of the rooms that overlap the cell. Then you could use the player's position to lookup the cell, which would then have a linked list of the rooms to test. When in the middle of a room you would have only one item in the grid-cell's list. This could be the fastest approach for spatial partitioning if the balance of grid size and room size is correct.

Good luck
> 6 votes

# Answer
To test whether a point lies inside of polygon you have some options, best known crossing number algorithm or more "stable" winding algorithm(there is pretty fast implementation too).
Alternatively, you can also use some of spatial partitioning algorithms too, most notably BSP-type. While spatial partitioning will probably offer superior query performance, it will require dynamic updating structure(if rooms can be changed later) - there are dynamic variations of those algorithms, but it will be *significantly* harder to implement.
> 8 votes

---
Tags: c#, 3d, geometry, geolocation
---


title: Sounds make Andengine Scene junky

text:
# Question
Title: Sounds make Andengine Scene junky
I have a `GameScene` which has a character (animated sprite), `AutoParallaxBackground` background with quite large textures and no more than 3 other items attached to the scene at a time, previous 3 items are `dispose()`-ed accordingly, background music and item sounds. Background music is instantiated with `MusicFactory`, Sounds are played on `SoundPool`. In between switching these scene we are loading resources asynchronously, reading the streams and instantiation is done in `AsyncTask` and the loading textures to the hardware is done on `UpdateThread`/`GLThread`. If I turn off the background music, this starts to happen totally random.

I'm experiencing scene junking on at first flow: `MenuScene` -\> 1st Stage (`GameScene`). After a while lag does not happen, rather than occasionally or random. Junk is happening when aforementioned 3 items are attached on the Scene and a sound is played along, note that background music is playing at the same time.

Detaching previous 3 items is "optimized" to reduce GC calling almost perfectly. When the lag occurs `GC_EXPLICIT` is showed in the logcat.

What I have tried:

* Playing the sounds and music on different thread, `IntentService`, dedicated Service.
* Reduced calls to `mScene.detachChild(child)` and other scene methods to avoid iterations over children of the scene.
* Detaching `IEntity`s with matcher to avoid iteration.
* Inspected sound files' integrity with ffmpeg for possible errors

Could `.dispose()`, unloading the textures from hardware or `detachChild()` causing this junk?

Could be marked object for GC from the async tasks be causing this?

What else could be contributing to this issue?

# Answer
After we have optimized the attaching and got rid of unnecessary look ups for scene children we've gained more fps as we advanced.

Occasional hiccups that were caused by `GC_EXPLICIT` were happening because `Font` in `update()` was explicitly calling `System.gc()`. Removing this line we were back on track below the green line, yeah! 60fps.

However, the author of AndEngine might had reasons for this explicit call. Since the stages are short we granted our app call this `gc()` when the `GameScene` is paused, quit or stage complete, anywhere where there is no excessive animation.

**Edit**:

Another thing that could contribute to the fps drop is the `SoundPool`. Every time `SoundPool` is done playing with sounds in the pool, it resets its state to idle perhaps, when the next sound is played it takes a 8ms+ to reload its state to different state than idle. To avoid this you need to play looping sound with 0 left and right volume.
> 1 votes

---
Tags: android, andengine, android-studio
---


# Question
Title: Unity's Quaternion.Lerp slows down when target is directly behind turret
Software: Unity v5.2.1f1 Personal

I am trying to achieve the effect of a turret in Unity. For this I have a turret consisting of 3 parts as well as a target. The problem is that whenever the target my turret is targeting has a z of \< 0, the lerp *speed* is extremely slow. However, the further away the target is from x=0 (both positive and negative), the faster it will move. This effect only occurs when my target has a transform.position.z of \< 0. When z \> 0 the transform.position.x has no effect on the lerp *speed*. My setup is as follows:

The 3 turret parts are the **base**, **turret** and **barrel**.

The **base** is nothing more than a block for the **turret** to rest on. The **turret** is a block holding the barrel in place with **base** as his parent. The **turret** rotates around its *y-axis* to always face the target. The **barrel** has **turret** as his parent. The **barrel** rotates around its *x-axis* to always face the target. See the picture below for the end result.

*Base: Blue; Turret: Red; Barrel: Green;*

The **turret** has the following code:

```
public class turretRotation : MonoBehaviour {

    public Transform target;

    void Update()
    {
        Vector3 relativePosition = target.position - transform.position;
        relativePosition.y = 0;
        Quaternion rotation = Quaternion.LookRotation(relativePosition, new Vector3(0, 1, 0));
        transform.localRotation = Quaternion.Lerp(transform.localRotation, rotation, Time.deltaTime);
    }
}

```

The **barrel** has the following code:

```
public class barrelRotation : MonoBehaviour {

    public Transform target;
    public float speed = 1;
    Vector3 relPos;
    Quaternion rot;

    void Update () {
        // Position of target relative to my position
        relPos = (target.position - transform.position).normalized;

        rot = Quaternion.LookRotation(relPos, new Vector3(0,1,0));

        // Lerping localRotatiot > rot with speed: Time.deltaTime * speed (set to 1 by default)
        transform.localRotation = Quaternion.Lerp(transform.localRotation, rot, Time.deltaTime *  speed);

        // Resetting y- and z-EulerAngles to 0; This way only the x-EulerAngle will be affected.
        // The y rotation is inherited from the parent (turret_turret)
        transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, 0, 0);
    }
}

```

*In this picture the Lerp is working as intended; Note target.transform.z \> 0*

*In this picture the target has a z = -5 and x = 0; pay particular attention to the Lerp speed*

It eventually gets there, but it takes a *very* long time. For some reason, the further away the target is from x=0, the faster the Lerp speed. *Note: Still slower than intended*

*In this picture the target has a z = -5 and x = -10*

So for some reason when target.transform.z has a negative value, the higher the distance from target.transform.x to x=0 the higher the Lerp *speed*.

I've done a fair bit of searching and came across a post on answers.unity.com describing a similair problem; Unfortunately, no reply. http://answers.unity3d.com/questions/1084067/lerp-problem-when-target-is-behind.html

**So my question is: "Why is this happening and more importantly, how can I fix this?"**

Any help would be much appreciated!

# Answer
> 4 votes
Taking a look at your barrel rotation function...

```
relPos = (target.position - transform.position).normalized;
rot = Quaternion.LookRotation(relPos, new Vector3(0,1,0));

```

`relPos` is in world space, so `rot` is an absolute rotation (ie. relative to the *world coordinate frame*)

```
transform.localRotation = Quaternion.Lerp(
      transform.localRotation,
      rot,
      Time.deltaTime *  speed);

```

transform.localRotation is relative to the *parent's coordinate space*.

**So this Lerp is blending between a relative orientation and an absolute one**.

When you use Lerp this way, the speed or increment each frame is proportional to the difference between the start & end values. (This adds a nice bit of slowing as the rotation approaches the target compared to `Quaternion.RotateTowards()` which enforces a particular speed)

Assuming your barrel is already pointing somewhat near your target...

* When the parent's rotation is very similar to the world coordinate frame, the difference between transform.localRotation and rot will tend to be small (slow tracking).
* When the parent's is rotated a lot relative to the world coordinate frame, the difference between transform.localRotation and rot will tend to be very large (fast tracking).

So you'll want to make sure you're using apples-to-apples comparisons when Lerping - either work entirely in local space (eg. with `transform.parent.InverseTransformDirection(relPos)` or `Quaternion.Inverse(transform.parent.rotation)` ) or entirely in world space.

---
Tags: unity, quaternion, lerp
---


title: Unity 5 C# collision problems

text:
# Question
Title: Unity 5 C# collision problems
I want to make the built-in FPS controller collide with an object and switch a boolean to true. Here is my code:

```
public static bool WellGUIOn;

// Use this for initialization
void Start () {
    WellGUIOn = false;
}

void OnCollisionEnter (Collision c)
{
    if (c.gameObject.name == "Well") {
        WellGUIOn = true;
    } else {
        WellGUIOn = false;
}

```

I have attached this script to the FPS controller and added a box collider on both prefabs (with is trigger ticked). The FPS controller already has a rigidbody(with kinematic ticked) and I added a rigidbody (with kinematic **NOT** ticked) to the object. Unfortunately, it doesn't work. How can I solve this?

# Answer
First of all, it is always a good idea to use `Debug.Log()` when something goes wrong.

```
void OnCollisionEnter (Collision c)
{
    Debug.Log("Collision: " + gameObject.name + " | " + c.gameObject.name);
    if (c.gameObject.name == "Well") {
        WellGUIOn = true;
    } else {
        WellGUIOn = false;
}

```

You can now see if the function is called the way you intended.

---

> added a box collider on both prefabs (with is trigger ticked)

Assuming you are using 3D and not 2D, I think you might want to use `OnTriggerEnter()` instead of `OnCollisionEnter()` then?

```
void OnTriggerEnter(Collider c)
{
    Debug.Log("Trigger: " + gameObject.name + " | " + c.gameObject.name);
    if (c.gameObject.name == "Well") {
        WellGUIOn = true;
    } else {
        WellGUIOn = false;
}

```

If you want to read more about Unity's collision system, here's the Colliders Overview.
> 0 votes

# Answer
In 2d mode, you must use `OnCollisionEnter2D`.

Example:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour  {

  void OnCollisionEnter2D(Collision2D coll) {
    if (coll.gameObject.tag == "Enemy")
      coll.gameObject.SendMessage("ApplyDamage", 10);
  }

}

```
> 0 votes

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


title: How are loot box labels positioned?

text:
# Question
Title: How are loot box labels positioned?
Take this screenshot for example:

How exactly are they positioned perfectly adjacent to each other? Do they already create the label positions based upon the world map first, and then when the player drops an item it fills the space? Or do they use a simple padded array function server-side and some custom algorithm to position them right next to each other. I have a feeling I'm totally overthinking this.

I am using nodejs w/ the Phaser framework for my web based game and am stuck at how they accomplish this server-side. (Since all players in-game see the same exact position)

# Answer
> 4 votes
I don't know the exact approach used in games like Diablo, but this problem is actually interesting enough to be given its own name (Automatic Label Placement), for which the general problem is NP-Hard. This means that there's copious amounts of material online, like this paper for example. It's a problem that occurs a lot in map labelling, so you may find this SO question useful.

My guess is that the algorithm used in your screenshot is some form of multi-foci force layout. See how there are labels over water, despite there being no loot boxes in water. It's likely that those labels were pushed out of place by the labels near the centre of the screen. This algorithm works by first placing all the labels near their boxes, then simultaneously repelling labels that overlap, and attracting labels back to their loot boxes. When the forces reach equilibrium, stop.

For loot box labels, a specific requirement would be that labels for items from the same box should be stacked together. You could enforce this by never allowing labels from the same box from splitting apart.

---
Tags: algorithm, ui-design
---


# Question
Title: Unity: Interactive menu with sprites changing with buttons
I have a menu where the player gets to choose which team and kit he will use to play. However I don't really know how to change the sprite each time the left or right arrows are pressed. I already have the sprites for each team, league and kit the only thing I am missing is the way to arrange it via script. Thanks.

# Answer
You can store all sprites in a array and have a index for selected team for example something like this:

```
List<Sprite> Slist;
int Index = 0;
if(user press next)
    flagObject.GetComponent<SpriteRenderer>().sprite = Slist[Index++];
if(user press previous)
    flagObject.GetComponent<SpriteRenderer>().sprite = Slist[Index--];

```

Although you should check for Index to not going out of bound.
> 1 votes

# Answer
You can do that using Unity UI's Scroll rect. Trick is to use a mask so that only one element can be displayed at a time. Refer Scroll Rect
> 0 votes

---
Tags: unity, menu
---


# Question
Title: Building placement in tilemaps (pattern matching)
I'm building a small RTS and in my code I've given my buildings a pattern, much like you would pieces in tetris, i.e. I want to place irregularly-shaped buildings on a map without overlaps.

The map could be 100x100 and my structure that I'm placing could be as follows:

```
OXO
XXX
XXX

```

I'm currently bruteforce-checking each building cell individually against cells in a map.

Is there an easier/nicer way to check a tile map for a matching pattern?

# Answer
> 1 votes
One simple and really fast way to do pattern matching is to use *bitsets*.

Let's say your map is 8x8 tiles: each bit represents either occupied (1) / non-occupied (0), e.g.

```
00000110 //least significant bits (0-7)
00000110
01111110
01101110
01100110
01100000
01100000
00000000 //most significant bits (56-63)

```

This fits into a single 64-bit integer (in most languages these days "long" or "unsigned long int").

Now you want to see if you can place a hut in the middle of the map:

```
00000000
00000000
00000000
00011000
00011000
00000000
00000000
00000000

```

To see if you can build here:

```
uint64_t map = ...; //top    arrangement of bits, above
uint64_t hut = ...; //bottom arrangement of bits, above
//...to convert these bitfields into uint64_t values, we use notation 0b00001... etc. up to 64 bits.
uint64_t canBuild = !(map | hut); //logical NOT and logical OR
if (canBuild) {...} //go wild!

```

...which to our minds means, "if there's nothing in the way at any of the locations that the proposed hut will occupy, you can build there". In this example the result of `map | hut` would be:

```
00000000
00000000
00000000
00001000
00000000
00000000
00000000
00000000

```

...so one of the tiles is blocked - you can't build there (logical NOT turns non-zero to zero / false).

You mentioned a 100x100 map. In this case we use a 13x13 array of 64-bit ints as above to represent the bigger map (making 104x104 tiles). The only slightly complex part of this is trying to compare against an area that borders on 4 64-bit sets, to see if you can place a building there. In this case you'll have to make 4 bitwise checks against all these neighbouring regions.

In order to write individual bits in `(x,y)` format as the patterns above, you'll need to do a little bit of googling of *bitwise logic*. Once you have it working, just wrap it in a function like:

```
void writeBitAt(uint8_t x, uint8_t y, bool value)
{
    //...left as an exercise for the reader...
}

```

**Are bitsets faster?** Much. Comparing 64 tiles of your map to another 64 tiles in one or two CPU cycles is many times faster than comparing a sequence of tiles via conditionals within a loop, which could easily cost hundreds of cycles when you consider the impact of conditionals on the pipeline.

**P.S.** If your language / platform only provides 32-bit integers, you can still make this work, it's just a little less intuitive, e.g. a 16x4 map could be as follows, the layout is entirely up to you:

```
0000011000000000
0000011000000110 //...end of first 32 bits
0000000000000110
0000000001100000 //...end of second 32 bits

```

# Answer
> 0 votes
Okay, so I'm not 100% on what your trying to achieve but I think I got the gist, here's a few ideas to get you going:

* First off you could easily cut down a lot of your algorithms calculations by adding each cell populated by a building, into a closed cell list. Then run the same calculations but on that list only.
* Another approach could be to use a Quadtree data structure, again this is greatly cut down the calculations, this may work better in the sense you could grab a chunk of your map cells containing the building and run your pattern matching algorithm just like you were doing for the whole map.

---
Tags: tilemap, rts, patterns
---


# Question
Title: Interaction between GUI and character(s)
This is more a question about architecture. Not sure if there's a right or wrong:

Let's assume I have some gameobjects:

* GUI: A menu containing some elements like "Go to position". It's opened when right clicking in the game
* Main Camera
* Characters: Characters in the game which can be controlled by the player

Now I was thinking about the following scenarios:

1. A character is clicked. It's highlighted yellow. This should definitely be done in the script of the character.
2. When a character is highlighted (or selected) and the right mouse button is clicked, the GUI will be shown. Where does this have to be implemented when talking about clean code? In the character? But then the character has to know about the GUI. I'm not sure if this is clean. In the GUI? Then then the GUI has to know if a character was highlighted (or selected). Doesn't feel clean too.

# Answer
Have you considered implementing the observer pattern? http://gameprogrammingpatterns.com/observer.html
> 1 votes

# Answer
In your case I'd add an "Input Watcher" component to the Main Camera (or similar Game Object).

To me the Input Watcher component is in charge of watching every player input and react accordingly. In your case, the Character component would inherit from, let's say, iSelectableObject (an interface that allows you to select the Character with the mouse or any input).

Once you click on the Character the Input Watcher component would know what you're trying to do and select the Character because it inherits from iSelectableObject (the Select() method of the Character would be called and the Character would display the yellow border you want it to show). Input Watcher now knows that an iSelectableObject object is selected and can now display the right GUI according to the type of the object. In your case it would be the button "Go to position".

To avoid having a gigantic list of if/else I usually use a state machine in the Input Watcher component to call and update the right state at the right time.
> 0 votes

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


title: Simple Diminishing Return with Cap

text:
# Question
Title: Simple Diminishing Return with Cap
**Problem**

Player obtains 5 points per level up to level 80 with a maximum of 400. There are 5 stats to be distributed to and no maximum limit to how much you can add to a stat.

* Strength
* Endurance
* Intelligence
* Agility
* Luck - Grants critical chance and critical damage

I would like to implement a diminishing return equation on let's say Luck. For critical chance, I do not wish for the player to be able to hit 100% critical chance.

There will be a ceiling to which it will reach as the increasingly decreasing growth reaches towards 0 per point added.

Example if the maximum critical chance I want the player to have is 40%, Each point into luck will increase critical chance lesser and lesser, until the critical chance reaches around 40%. By which 1 luck will give a very very miniscule amount.

Any solutions? Thank you and your help is greatly appreciated!

# Answer
> 36 votes
You want to start with an asymptotic function. That is, one that starts at a number `a` and approaches another number `b`, but never actually reaches it. It's probably going to be easiest if `a = 0` and `b = 1`. You'll take this equation, input the number of stat points (Luck points) the character has, and get the actual stat value (Crit Chance) as the output.

A very simple example is `y = x / (x + n)` where `n` is some positive constant. Here `x` is your input, where you feed in the number of stat points, and `y` is your output, where you get the final stat value.

For `n = 5` check out what it looks like:

When you feed in `x = 0` you get `y = 0`, but no matter how big an `x` you put in, `y` never quite reaches 1. Perfect.

Now, you can tune this to your hearts desire. You can multiply by a scale factor to set the 'cap' to whatever you want. `y = a * x / (x + 5)`. If you want the cap to be 40%, multiply by .4. `y = .4 * x / (x + n)`. Now when you feed in `x`'s, `y` will increase but it will never quite reach .4.

Adjust `n` to set how fast or slow the equation ramps up. `n = 100` is going to increase a lot slower than `n = 5`:

You can solve this equation for `n` if you know you want the stat value you want to reach at a specific number stat points. Let's say the character should have 35% Crit Chance at 100 points of Luck. Solving `.35 = .4 * 100 / (100 + n)` for `n` yields `n = 14.29`.

These numbers don't have to be raw constants either. Maybe other stats go into calculating the values of `n`. Maybe some characters have different `n`'s so they scale better in their 'preferred' stat.

If you want a curve that's shaped differently or is more complex, there are many other examples of asymptotic functions you could use as well. I'll leave you to explore that as you wish.

# Answer
> 11 votes
A good base would be a function like `arctan`, since it passes through the origin and exhibits a horizontal asymptote.

Scale it by `40 / (pi/2)`, or `80/pi` for your desired limit. Then transform `luck` to get the curve steepness that you want.

```
critical = 80/pi * arctan(f(luck))

```

# Answer
> 10 votes
I really like the way that the Souls games tackle this problem. Rather than making each stat give bonuses based on a continuous function as has been suggested, it gives bonuses in a piecewise linear function.

I can't remember the exact numbers off the top of my head, but the functions are along the lines of the following (each stat has its own constants)

This method provides many benefits to the designer and the player. The designer benefits as you can tune the exact benefit per point in a skill fairly trivially, and the player benefits as they know exactly how much benefit they will see from level to level.

In the case of a continuous function, some levels might give a benefit that doesn't get reflected in the numbers due to measurement aliasing. Sure that last level gave you a 0.9 increase in bonus XYZ, but since the actual value went from 23.52 to 24.42, and you round the number prior to displaying it, the player doesn't realize something has changed.

From a UX perspective, I would definitely suggest going with a piecewise linear function. However, using a continuous function can be easier to tune later down the line, as players won't be as attached to round constants.

# Answer
> 4 votes
Jan Dvorak points out the exponential function in a comment. I'll explain it here.

Note that exponential (and trig) operations are considerably more computationally expensive than even square root operations, which are themselves far worse than basic math, so you're probably better off with Adam's approach if you'll be doing these calculations many times per second. If you just calculate the values when the player levels, changes equipment, etc., speed isn't important, so use whatever gives you the best curve.

An exponential function is some base, *B*, to some power, *x*, `y=B^x`. Mathematicians commonly use a base of *e*, (~= 2.718), but there's no reason you can't use 2 or 10 if you prefer.

`y=e^x` looks like this:

Notice the left side is moving asympotically to 0. So we can flip the x-axis by doing `y=e^(`**-**`x)`, but it's still descending from 1 to 0 and we want it to ascend. So we can flip it across the y-axis with `y=`**-**`e^(-x)`. Now it's ascending from -1 to 0. We can add 1 to get `y=`**1**`- e^(-x)` and it's ascending from 0 to 1.

From here, it's just a matter of scaling it vertically and horizontally. We can multiply the entire thing by some value, let's call it *A*, that sets the asymptotic limit. Then we can multiply *x* by a rate-of-change value, *k*, to adjust how quickly it closes in on the limit.

This gives us a final equation of `y=A*(1 - e^(-k*x))`. Using values of `k=0.012` and `A=0.5`, we can set the limit to 50% and let it get pretty close to that limit around `x=400`.

Now, you can make a few tweaks to this. One tweak I made was changing to `A=0.5041`, so if we round to a percentage with 2 decimals (like 32.23%), y(399) = 49.99% and y(400) = 50.00%. From y(347) onward, there are several places where it takes two points to get a change of 0.01%. But that last possible point still gives a (barely) tangible benefit, and brings it to an even 50%.

Alternately, we could tweak the `k` value to have a similar effect. At `k=0.02305`, the value rounds to 49.99% at `y=399` and 50.00% at `y=400`. However, this has the problem that the graph is *very* shallow at the end -- it takes 48 points to get that last hundredth of a percent (from `y(352)=49.99%` to `y(399)=49.99%` to `y(400)=50.00%`) and the last 1% crit chance takes a whopping 230 points (from `y(170)=49.01%` to `y(400)=50.00%`) which is probably a bit too diminishing on returns.

If you wanted, you could adjust both A and k so it's diminishing to a somewhat higher limit at a slower rate, to give something between linear and exponential decay. Doing `y=0.6*(1-e^(-0.00447*x))`, you end up with this:

Note that the curve continues past 50%, but since there's a hard limit of 400 rating, the player can't pass that point (and if they do manage to pass it, there's still a hard limit of 60% crit). With this equation, you can use 1 decimal place and still see gains every 2 to 3 points, with a final tick from `y(399)=49.9%` to `y(400)=50.0%`.

Mathematically, the earlier equations might seem better, since they're actually approaching 50%, but I personally think gains of 0.1% every couple points feels better than gains of 0.01%. Even with `A=0.05041` and `k=0.012`, it takes 102 points to go from `y(298)=49.00%` to `y(400)=50.00%`. 25% of your points spend on 2% of your crit is probably too diminished. The 60% equation only takes 20 points for the last percent (which is still 5 times higher than the 4 points needed for the first percent).

With these last several equations, I just plugged the equations into a spreadsheet and manually tweaked values until they looked good. You'd have to do something similar if you wanted a different cap.

# Answer
> -1 votes
For a very simple solution, how about square root x 2

The square root of 400 (max possible) is 20, 20\*2 = 40.

---
Tags: rpg
---


# Question
Title: How do I show the ranking images at winning post?
I am working on a racing game in Unity3d and I have to show the rank as the winners touch the winning point.

As the winners reach at the winning point the image of the winner number should pop up for 1-2 seconds that is it.

How do I do it? Can anyone sort out this problem? Any help would be appreciated.

Thanks in advance :)

# Answer
Set a script like the following, on your game object that will be used to display this text.

I don't know anything about your design, so take this as a starting point.

```
float Timer = 2;
bool Active;

void Start()
{
    SpriteRenderer = GetComponent<SpriteRenderer>();
    SpriteRenderer.enabled = false;
}

public void SetActive()
{
    Active = true;
    Timer = 2;
    SpriteRenderer.enabled = true;
}

void Update()
{
    if (Active)
    {
        Timer -= Time.deltaTime;
        if (Timer <= 0)
        {
             SpriteRenderer.enabled = true;
             Active = false;
        }
    }
}

```
> 1 votes

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


title: Draw transparency

text:
# Question
Title: Draw transparency
I want to draw a terrain in a `Texture2D` at runtime in order to make collisions work with Farseer Physics later on.

What I need is to make some parts of my original texture, which is just a colored rectangle, transparent. Unfortunally this is as straightforward as I thought it would be. Here the code that does not work:

```
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, 800, 480);
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.CornflowerBlue);

spriteBatch.Begin();
spriteBatch.Draw(textureTerrain, new Vector2(0, 200), Color.White);
spriteBatch.Draw(textureCrate, new Vector2(0, 300), Color.Transparent);
spriteBatch.End();

```

As you may think with this code XNA is drawing an transparent texture on the screen, which is essentially nothing.

# Answer
> 2 votes
You could use `Texture2D.SetData` to modify a section of the texture. Fill the section with array of Color. Using your example code: the array should be the dimension of `(crate.width*crate.height)` filled with `Color.Transparent`. The target rectangle is `new Rectangle(0,300,crate.width, crate.height)`.

See: https://msdn.microsoft.com/en-us/library/ff434430.aspx

Another option is to use a custom blendstate, if your "crate" is not rectangular.

```
        GraphicsDevice.SetRenderTarget(Rendertarget);
        GraphicsDevice.Clear(Color.Transparent);

        BlendState TransparentBlend = new BlendState();

        TransparentBlend.ColorBlendFunction = BlendFunction.Add;
        TransparentBlend.ColorSourceBlend = Blend.Zero;
        TransparentBlend.ColorDestinationBlend = Blend.InverseSourceAlpha;

        TransparentBlend.AlphaBlendFunction = BlendFunction.Add;
        TransparentBlend.AlphaSourceBlend = Blend.Zero;
        TransparentBlend.AlphaDestinationBlend = Blend.InverseSourceAlpha;

        // Draw a Red rectangle to start with.
        spriteBatch.Begin();
        spriteBatch.Draw(Pixel, new Rectangle(0, 0, 200, 200), Color.Red);
        spriteBatch.End();

        spriteBatch.Begin(SpriteSortMode.Immediate, TransparentBlend, null, null, null, null, null);

        // Draw two sprites, slight overlap to demonstrate that combinations work.
        spriteBatch.Draw(Boy, new Vector2(20, 20), Color.White);
        spriteBatch.Draw(Boy, new Vector2(70, 20), Color.White);
        spriteBatch.End();

        GraphicsDevice.SetRenderTarget(null);
        //Cornflower color should show through the gaps.
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        // Show the resulting sprite
        spriteBatch.Draw(Rendertarget, Vector2.Zero, Color.White);
        // Show the Boy sprite as reference.
        spriteBatch.Draw(Boy, new Vector2(220, 20), Color.White);
        spriteBatch.End();

```

In the example I used `Pixel`: a 1x1 white texture and Boy is a texture from the http://www.lostgarden.com/2007/05/dancs-miraculously-flexible-game.html tileset.

The above code produces this:

# Answer
> 2 votes
You can use custom effect to do it. If you need draw texture without all pixels of some known color then pass this color to your shader and then clip texture pixels that have same color. In other case if parts you want make transparent have different colors you can create texture mask use it in your shader to determine what pixels should be cliped.

An axample (original link):

In this case "layer 1" is mask. Parts that are wite determine where base image pixels should be replaced to pixels from texture "layer 0". In your case you can just clip it.

See here how create and use own effects.

And there is shader that can help you *(sorry for possible mistakes, writen in notepad)*. I'm combined both ideas in one shader. Use mask color and/or mask texture as you wish.

```
texture TextureMap;
texture MaskTextureMap;
float4 MaskColor;

sampler TextureMapSampler = sampler_state // texture 0, same texture that you pass to SpriteBatsh.Draw()
{
    Texture = <TextureMap>;
};
sampler MaskTextureMapSampler = sampler_state // texture 1, you need to set it to shader before draw
{
    Texture = <MaskTextureMap>;
};

float4 PixelShader1(float2 pTexCoord : texcoord0) : color0
{
    float4 color = tex2D(pTexCoord, TextureMapSampler);
    clip(color == MaskColor ? -1 : 1); // discard pixel if it's color is same as mask color

    float4 maskMapColor = tex2D(pTexCoord, MaskTextureMapSampler);
    clip(maskMapColor.a == 1 ? -1 : 1); // discard pixel if mask is not transparent at that texture coords

    return color; // return color from texture map if not cliped; else pixel will be transparent
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShader1();
    }
}

```

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


# Question
Title: How can I minimise memory thrashing when doing vector math in JavaScript or ActionScript?
Please note that a similar question has been asked before in the context of C#.

Say I'm building a 3D game in Javascript or Actionscript, and doing a lot of 3D vector math. In current libraries, every operation causes a new object to be created and returned as the result value. What is a simple way to optimize this?

For example in this snippet, 2 new Vector3D objects are created, one at the divide and one at the multiply operator.

```
// JS
result = v.divideBy(len1).multiplyBy(len2);

```

A better approach would be creating a single object and reusing it.

```
// JS
var _temp = {x:0, y:0, z:0};  // create a single object once
....
v.divideBy(len1, _temp);       // re-use it
_temp.multiplyBy(len2, _temp); // re-use it

```

In C# you could just use structs, but in languages like JS and AS3 there are no such things. What does one do to minimise object creation in such languages?

**Edit:** For example currently I'm doing BSP partitioning in the browser, and its very slow during the BSP operation. (I have profiled to confirm this) I have discovered that the major cause is vector math, and the GC that occurs often that also causes stutters.

**Edit:** Please note that my question can apply to any type of object in general, not just vector math. So when I'm creating millions of objects as a return value of any function, performance would be affected. Therefore, I am looking for better design patterns to solve the very common issue of returning multiple values.

# Answer
A possible approach that could be very quick is to create one or more webworkers for your computational tasks. A webworker doesn't share any memory with the main thread or other webworker, so it won't pollute the global memory.

If you need a quick and dirty solution without much rewriting or choosing another library, you could try it that way.

P.S.: I would have liked to add this as a comment, but can't due to missing reputation.
> 2 votes

# Answer
As with your other question, I think you need to profile your code and assess the bottlenecks. Languages like Javascript, which perform significant allocations by design of the language, have efficient allocators and garbage collectors. I would argue that the design of your library is wrong. There are a number of effective libraries out there that use the same syntax. Here's one: http://sylvester.jcoglan.com/

And sample syntax:

```
var V1 = $V([3,4,5]);
var V2 = $V([9,-3,0]);

var d = V1.dot(V2);
// d is 15

var c = V1.cross(V2);
// c is the vector (15,45,-45)

```

or http://victorjs.org

```
var vec1 = new Victor(100, 100);
var vec2 = new Victor(200, 200);

vec1.dot(vec2);
// => 40000

```

Simply citing a language's need to allocate temporaries isn't fair when a language is designed around fast, generational allocations and garbage collectors, as you'll find in modern javascript implementations. I would go and profile where the bottlenecks are and be sure it is the allocations, first.
> 1 votes

---
Tags: mathematics, javascript, performance, actionscript-3, memory
---


title: Rotating sprite around another sprite

text:
# Question
Title: Rotating sprite around another sprite
I am building a pool game, and I want to make the cue rotate around the white ball.

Here is the live code:

http://199.26.84.223/nocol.html

Here is the code for the white ball:

```
balls = game.add.group();
balls.enableBody = true;
balls.physicsBodyType = Phaser.Physics.P2JS;
wball = balls.create(350, 240 , 'ballW');
wball.body.setCircle(15);
wball.body.setCollisionGroup(wballCollisionGroup);
wball.body.collides([wballCollisionGroup, ballsCollisionGroup , sidesCollisionGroup , holesCollisionGroup , playerCollisionGroup]);
game.physics.p2.setImpactEvents(true);

```

Here is the code for the cue, which I call `player`:

```
    player = game.add.sprite( 0   , 0   , 'player');
    game.physics.p2.enable(player , true );
    player.enableBody = true;
    player.body.setCollisionGroup(playerCollisionGroup);
    player.body.setZeroVelocity();
    player.body.createBodyCallback(wball, ballHit , this);
    player.anchor.setTo(-0.5, 0.5);
    player.pivot.x = wball.x +150;
    player.pivot.y = 0;

    player.body.x = wball.x  ;
    player.body.y = 240 ;

```

The problem is that all pivot or anchor does is change the sprite image position. I got the cue to appear in the right place by using both pivot/anchor and it seems to work fine... the cue was rotating around the ball, but after enabling debug mode here is what I saw:

Basically only the position of the image has been changed but the sprite still rotates around the center which is the red part. If I run this code, the ball and cue are already colliding and the ball jumps around without player doing anything.

How can I rotate the cue around the ball without them colliding?

# Answer
I've never used Phaser but did a quick look at the documentation. The Achor.setTo you are using seems to only offset the texture, so it's not what you need.

I couldn't find any Vectors or Matrices in the docs but you should create a rotation matrix with the angle of the cue. Something like this:

```
var myMatrix = Matrix.RotationY(userDefinedAngle);

```

Then with some vectors you can get the new cue position.

```
var offsetVector = Vector2(distanceToBall, 0);
var newpos = Vector2.Transform(offsetVector, myMatrix);

```

Now create a vector pointing to the ball from the cue position.

```
var direction = ballPos - newpos;
direction.normalize();

```

this direction vector is the one you apply when the player shoots, instead of just adding to x like you do today.

```
if (cursors.down.isDown )
{
    player.body.velocity += direction * someSpeedValue;

}

```

Please note that I have no idea if the methods or objects work like this but I would be very surprised if there weren't something similar in Phaser.

**Edit.**

PIXI.Matrix seems to be the objects you need, please look into that.
> 1 votes

# Answer
You are manipulating the sprite, but not the underlying body. The sprite affects the visual appearance while the body affects the physics behavior.

---

There are a number of ways you can fix this:

**Quick hack:** *I am not sure if this will work and I recommend one of the other solutions, but this might get your desired result with the least amount of effort:*

Each time you adjust the sprite with `pivot` and/or `anchor,` call `setRectangleFromSprite()` to realign the physics body with the new sprite position.

```
player.anchor.setTo(-0.5, 0.5);
player.pivot.x = wball.x +150;
player.pivot.y = 0;
player.body.setRectangleFromSprite();
player.body.setCollisionGroup(playerCollisionGroup);  // setRectangleFromSprite() may reset the collision groups

```

**Slightly more elegant solution:** *Takes advantage of the simple relationship between the cue stick and cue ball to avoid some hairy trigonometric math.*

* Keep using `pivot` and `anchor` to visually show the cue rotating/moving, but don't add a physics body to this sprite.
* Handle the collision between the cue and the white ball by manually adding a force to `wball.body` based on the speed and orientation of the cue about the time they "hit."
* Use `wball.body.applyImpulse(...)` or `wball.body.applyImpulseLocal(...)` depending on how you calculate the location of the collision (relative to the the world or the cue ball?)

**Physically most accurate solution:**

Instead of modifying `player.anchor` and `player.pivot` to move the cue stick, modify `player.body`. The sprite is automatically adjusted to move/rotate along with its physics body.

* Instead of `anchor`, change `player.body.x` and `player.body.y` to alter the cue stick's position.
* Instead of `pivot`, change `player.body.angle` or `player.body.rotation` to alter the cue stick's rotation.
* Getting the cue stick to rotate around the ball will not be as simple as using `anchor` and `pivot.` It will require some trigonometric calculations to place the cue stick at an appropriate position and angle relative to the cue ball!
> 1 votes

# Answer
If you make the x/y set to the sender of the white ball, and then add padding (not a lot, but enough to make it balance on the outside of the white ball). Or instead of padding, make the cue have a small area of unused space, just enough to make it balance on the outside of the white ball
> 0 votes

# Answer
As your sprite is in the desired position, you should try to define a collision body for it manually.

```
player.body.clearShapes();
player.body.addRectangle(300, 20, 0, -150); // trial an error the values
player.body.updateCollisionMask();

```

The addRectangle method takes the following parameters:

```
addRectangle(width, height, offsetX, offsetY, rotation)

```

See here.
> 0 votes

---
Tags: 2d, physics, html5, html-canvas, phaser
---


title: Find out hit child with RaycastHit

text:
# Question
Title: Find out hit child with RaycastHit
Let's assume having a (2d-) gameobject with 3 images: Head, body, feet. By using `RaycastHit2D` I can find out if the gameobject was hit (for example by the mouse):

```
RaycastHit2D newSelectedObject = Physics2D.Raycast(cameraVector, Vector2.zero);

```

Now I'd like to find out if the head, body or feet was hit. How can I do that?

# Answer
> 3 votes
2D objects can not be checked for collision with mouse using that code. This code is working only when you cast a ray on a 2D plane and it comes from side of an object.

But when you want to check 2D object being hit by mouse you need this:

```
Ray pressRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.GetRayIntersection(pressRay, Mathf.Infinity);
GameObject hitGameObject = hit.transform.gameObject;

```

Anyway, when you check for collision you need to traverse RaycastHit2D structure to find GameObject that is affected by hit either using `hit.transform.gameObject` notation or `hit.collider.gameObject`.

I advise to attach colliders to each child, set `IsTrigger = true` and use second notation.

---
Tags: c#, unityscript, unity, raycasting
---


# Question
Title: Exponential EXP Curve | FIXED TIME -> MAX LEVEL
I have yet another experience equation question, with a slight twist.

**Problem Situation**

Player gain experience from Level 1 - 80.

Time to level from Level 1 to 80 grows exponentially.

There is a constant of total hours X (540 hours in this case) to reach level 80.

**What equation results in this?**

From this, I should be able to balance an approximate Time To Kill Monster + downtime, varying from easy to hard monsters and experience they can give, resulting in same time to Max Level.

Or I could create quests that takes an approximate Time To Completion but rewards the same ratio of experience.

In my opinion this should be the optimum solution to create content that grant the same ratio of experience to time to level.

Thank you.

# Answer
> 3 votes
The general form of an exponential curve like this one is:

```
H = a * r^n + k

```

where:

```
H = total hours to reach level n
r = the ratio by which the time increases from one level to the next
a = scales the curve to make sure it hits the desired max
k = shifts the curve to make sure H(1) = 0

```

Now we just need to plug in numbers to hit the desired start & end points:

```
a*r^80 + k = 540 (max)
a*r^1 + k = 0    (min)

```

Subtracting:

```
a*(r^80 - r) = 540
a = 540/(r^80 - r)

```

And from the min expression:

```
k = -a*r^1

```

So now you can choose a value of `r` that you like (something very slightly more than 1 - exponentials build up astonishingly fast over 80 levels!) - I found something in the neighbourhood of 1.05 looked pretty decent. Then you can calculate `a` from `r` and `k` from `a` & `r`.

In case you're interested, the time to reach level `n` from the previous level `n-1` is:

```
a * r^(n - 1) * (r - 1)

```

which we can verify grows by a factor of `r` each time we gain a level.

# Answer
> 0 votes
EDIT: After a misinterpretation.

After some brief algebra work, the equation you are looking for is Y = 1.0818197904022^x. With x being the level, and y being the required amount of hour. Note that this equation needs to start at 2. Reason, even if the player starts at zero, you are compounding the level exponentially onto the base hours. If you get a zero, the output is one. If you get one. The output is the base.

Remember that an exponential works by compounding it's base by it's self exponentially. Unless the graph is shifted (some additional logic will be needed to set things correctly), you'll have to logically compensate for this factor.

Exponential Graphs http://dwb4.unl.edu/Chem/CHEM869Z/CHEM869ZMats/ExpFns.html Other graphs. http://www.coolmath.com/precalculus-review-calculus-intro/precalculus-algebra/05-graphing-basic-graphs-04

---
Tags: java, game-design, mathematics, algorithm, rpg
---


# Question
Title: Reconciling external events with the game loop
Is there any way I can program (in Java or Python, but open to other solutions) some game logic based on events, timed and sent by player input, without dealing with it inside the game loop, by having a game state that has a number of scripts listening for events, and those scripts can themselves fire events that change the game states and by consequence the scripts listening for events? An example bellow

```
class BombScript {

    private GameObject bombReference;

    void bombDefused() {
        // change the script listening for events
        bombReference.destroy();
    }

    void bombExplode() {
        // launch some events, change the script listening for events
        stopListeningForEvent("bombDefused");
        bombReference.destroy();
        sendEvent("bombExplode", bombReference);
    }

    void bombPlanted() {
        // if somehow the server receives a defuse command
        onEvent("bombDefused").execute(bombDefused);

        // else, if 6 seconds pass without an "bombDefused" event
        onTimeout(6).execute(bombExplode);
    }
}

```

I'm having trouble imagining a concrete implementation for that, specifically the timed based "if/else"

# Answer
> 1 votes
The way I've handled this in arc in the past - particularly for the JS version where you can't possibly avoid having to handle external events of various sorts - is to use a service that specifically acts as a proxy to the world outside the game loop. These services listen on the relevant event dispatcher(s) and stack up incoming events, which are popped off at the earliest opportunity by the controller class(es) (the main actors of the game loop in arc and can access any service) and handled thereby. You could handle one or more such events in a single game loop frame.

Using services neatly *keeps this code away* from your main game logic which - as you rightly indicate - shouldn't be polluted by external event loops.

One thing I will say about this is that if receiving game state from a server or peer, you will want those events to represent deltas, *not* absolute state since it becomes that much harder to update your local data model if you have to compare the last and current state objects (i.e. the events) just in order to determine what has changed... caused me some initial headaches.

This was tested in production for a client's real-time app, so I imagine it would work fine for you.

# Answer
> 0 votes
I'm not sure if you are asking about the implementation or the usage of an event based system, so I'll touch on both.

The implementation of event systems can be complex, and varies greatly depending on the language, but it is generally doable. The link above to the (excellent) Game Programming Patterns' article on the Event Queue is one hint to an implementation. The Observer (Delegate) pattern is also related; instead of binding to events passed by a mediator object, you bind directly to events fired by your objects.

After you have some building blocks, the game logic part is just that - logic. In your specific time-based example, here's what I'd do:

1. Create a `Timer` class. It fires a single event: `TimerExpired`, when some given interval of time has elapsed after the timer is started.
2. Create a `Timer` object in the `BombScript` class. In `bombPlanted`, initialize the timer with a time of 6 seconds and bind `bombExplode` to its `TimerExpired` event.
3. In `bombExplode`, unbind from the `bombDefused` event (since that can't occur anymore) and explode the bomb. Additionally, reset the timer, but don't start it again.
4. In `bombDefused`, unbind from the timer's `TimerExpired` event and reset the timer. Now, the timer won't fire.

---

I can see one big problem with dropping the game loop: things won't be able to happen without events firing. This is important for things like physics and AI, which must act independently of player input. Of course, you could just make a timer that fires every 60th of a second to update those systems - but that's basically just re-implementing the game loop. Barring those issues, I think it is possible (although, perhaps, difficult) to implement the server the way you are planning.

---
Tags: events, timer
---


title: Raymarching on a Hi-Z buffer in GLSL

text:
# Question
Title: Raymarching on a Hi-Z buffer in GLSL
So I'm trying to implement Screen Space Reflections using a Hierarchical z-Buffer in GLSL. I'm following the approach from GPU Gems 5 and the Frostbite presentation linked here ("Stochastic Screen-Space Reflections", Slide 36+).

I believe I have a fundamental misunderstanding how the algorithm works, however there are not many information about this algorithm, besides of the resources I linked.

My current GLSL code looks like this:

```
vec3 trace_ray(vec3 ray_start, vec3 ray_dir)
{

    ray_dir = normalize(ray_dir);
    ivec2 work_size = SCREEN_SIZE_INT;
    const int loop_max = 250;
    int mipmap = 0;
    int max_iter = loop_max;
    vec3 pos = ray_start;

    // Move pos by a small bias to avoid self-intersection
    pos += ray_dir * 0.004;
    float hit_bias = 0.002;

    while (mipmap > -1 && max_iter --> 0)
    {

        // Check if we are out of screen bounds, if so, return
        if (pos.x < 0.0 || pos.y < 0.0 || pos.x > 1.0 || pos.y > 1.0 || pos.z < 0.0 || pos.z > 1.0)
        {
            return vec3(0,0,0);
        }

        // Compute the fractional part of the coordinate (scaled by the working size)
        // so the values will be between 0.0 and 1.0
        vec2 fract_coord = mod(pos.xy * work_size, 1.0);

        // Modify fract coord based on which direction we are stepping in.
        // Fract coord now contains the percentage how far we moved already in
        // the current cell in each direction.
        fract_coord.x = ray_dir.x > 0.0 ? fract_coord.x : 1.0 - fract_coord.x;
        fract_coord.y = ray_dir.y > 0.0 ? fract_coord.y : 1.0 - fract_coord.y;

        // Compute maximum k for which the ray would still be inside of the cell.
        float max_k_x = (1.0 / ray_dir.x) / work_size.x;
        float max_k_y = (1.0 / ray_dir.y) / work_size.y;

        // Scale the maximum k by the percentage we already processed in the current cell,
        // since e.g. if we already moved 50%, we can only move another 50%.
        max_k_x *= 1.0 - fract_coord.x;
        max_k_y *= 1.0 - fract_coord.y;

        // The maximum k is the minimum of the both sub-k's since if once maximum
        // is reached, the ray is out of the cell
        float max_k = min(abs(max_k_x), abs(max_k_y) );

        // Fetch the current minimum cell plane height
        float cell_z = textureLod(DownscaledDepth, pos.xy, mipmap).x;

        // Check if the ray intersects with the cell plane. We have the following
        // equation:
        // pos.z + k * ray_dir.z = cell.z
        // So k is:
        float k = (cell_z - pos.z) / ray_dir.z;

        // Check if we intersected the cell
        if (k > 0.0 && k < max_k + hit_bias )
        {
            // Move to point of intersection
            pos += k * ray_dir;

            // In case we are at mipmap level 0, we found a match
            if (mipmap == 0) {
                return pos;
            }

            // If we hit anything at a higher mipmap, step up to a higher detailed
            // mipmap:
            mipmap -= 2;
            work_size *= 4;
        }

        // If we hit nothing, move to the next cell, with a small bias
        pos += max_k * ray_dir * 1.02;

        mipmap += 1;
        work_size /= 2;

    }
    return vec3(0);
}

```

And the result is:

So I'm doing something wrong, its probably not much since the result is not completely off, however, I cannot figure out what I'm doing wrong.

**TL;DR: Am I either misunderstanding how the Algorithm works, or if not, what am I missing or doing wrong in my code?**

# Answer
Okay, I figured the error now, I thought I'd share the code I used so others can benefit from it:

```
vec3 trace_ray(vec3 ray_start, vec3 ray_dir)
{

    if (ray_dir.z < 0.0) {
        return vec3(0);
    }

    ray_dir = normalize(ray_dir);
    ivec2 work_size = SCREEN_SIZE_INT;

    const int loop_max = 150;
    int mipmap = 0;
    int max_iter = loop_max;

    vec3 pos = ray_start;

    // Move pos by a small bias
    pos += ray_dir * 0.008;

    float hit_bias = 0.0017;

    while (mipmap > -1 && max_iter --> 0)
    {

        // Check if we are out of screen bounds, if so, return
        if (pos.x < 0.0 || pos.y < 0.0 || pos.x > 1.0 || pos.y > 1.0 || pos.z < 0.0 || pos.z > 1.0)
        {
            return vec3(0,0,0);
        }

        // Fetch the current minimum cell plane height
        float cell_z = textureLod(DownscaledDepth, pos.xy, mipmap).x;

        // Compute the fractional part of the coordinate (scaled by the working size)
        // so the values will be between 0.0 and 1.0
        vec2 fract_coord = mod(pos.xy * work_size, 1.0);

        // Modify fract coord based on which direction we are stepping in.
        // Fract coord now contains the percentage how far we moved already in
        // the current cell in each direction.
        fract_coord.x = ray_dir.x > 0.0 ? fract_coord.x : 1.0 - fract_coord.x;
        fract_coord.y = ray_dir.y > 0.0 ? fract_coord.y : 1.0 - fract_coord.y;

        // Compute maximum k and minimum k for which the ray would still be
        // inside of the cell.
        vec2 max_k_v = (1.0 / abs(ray_dir.xy)) / work_size.xy;
        vec2 min_k_v = -max_k_v * fract_coord.xy;

        // Scale the maximum k by the percentage we already processed in the current cell,
        // since e.g. if we already moved 50%, we can only move another 50%.
        max_k_v *= 1.0 - fract_coord.xy;

        // The maximum k is the minimum of the both sub-k's since if one component-maximum
        // is reached, the ray is out of the cell
        float max_k = min(max_k_v.x, max_k_v.y);

        // Same applies to the min_k, but because min_k is negative we have to use max()
        float min_k = max(min_k_v.x, min_k_v.y);

        // Check if the ray intersects with the cell plane. We have the following
        // equation:
        // pos.z + k * ray_dir.z = cell.z
        // So k is:
        float k = (cell_z - pos.z) / ray_dir.z;

        // Optional: Abort when ray didn't exactly intersect:
        // if (k < min_k && mipmap <= 0) {
        //     return vec3(0);
        // }

        // Check if we intersected the cell
        if (k < max_k + hit_bias)
        {
            // Clamp k
            k = max(min_k, k);

            if (mipmap < 1) {
                pos += k * ray_dir;
                return pos;
            }

            // If we hit anything at a higher mipmap, step up to a higher detailed
            // mipmap:
            mipmap -= 2;
            work_size *= 4;
        } else {

            // If we hit nothing, move to the next cell, with a small bias
            pos += max_k * ray_dir * 1.04;
        }

        mipmap += 1;
        work_size /= 2;
    }

    return vec3(0);
}

```

Result:
> 1 votes

---
Tags: opengl, glsl, raycasting, depth-buffer
---


# Question
Title: How can C# access JavaScript variables in Unity 5?
I have a static public boolean in a JavaScript and I want to access it in a C# script. When I tried the way that you would call a static variable from another script though, it said that the variable and script weren't recognized. Here is my JavaScript code:

```
public static var ItemPurchased = false;
function OnGUI () {
    if (GUI.Button(new Rect(10, 90, 190, 24), "Click here to collect water.")){
         ItemPurchased = true;
}

```

I do believe that the JavaScript is correct. On the other hand, here is my C# script:

```
public static bool itemowned = false;
void Update () {
    if(PurchaseItemScript.ItemPurchased == true){
        itemowned = true;
        PurchaseItemScript.ItemPurchased = false;
    }
}

```

PLZ HELP!

# Answer
Looks like your *class* is not static. You need to initialize it before using:

```
public static bool itemowned = false;

private readonly PurchaseItemScript = new PurchaseItemScript();

void Update () {
    if(PurchaseItemScript.ItemPurchased == true){
        itemowned = true;
        PurchaseItemScript.ItemPurchased = false;
    }
}

```

or, make the PurchaseItemScript class static.
> 1 votes

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


# Question
Title: How do I implement tilt controls that work even when the device is not vertical?
I'm using libGDX to develop an Android game. The main character can be moved freely in the 2d plane by tilting the phone. The relevant part of my current implementation looks somewhat like this:

```
Vector2 mainCharacter;
float speedX, speedY;

public void render(float delta) {
    speedX = 0.6f * speedX + 0.4f * -Gdx.input.getAccelerometerX();
    speedY = 0.6f * speedY + 0.4f * -Gdx.input.getAccelerometerY();
    mainCharacter.move(speedX, speedY);
}

```

This simple implementation works quite well as long as the player sits or stands upright. But there are two situations where this approach fails:

1. If the player holds his phone almost horizontally (e.g. if he lies in bed, see fig. 1). Neither the computation of speedY nor the computation of speedX works properly in that situation.
2. Inside a moving vehicle. When the vehicle speeds up or slows down, this has a strong impact on the values returned by Gdx.input.getAccelerometerX/Y.

So my question is: Is there anything that can be done to solve these two problems? How can I get satisfying results independent of whether the player is lying, standing or sitting? And is there a reasonable way to reduce the influence that the movement of a vehicle has on the output of the accelerometer?

*fig. 1*

# Answer
I've not used the accelerometer's code but know some implications. What I suggest is that you save a variable with the original orientation, this can be set when the user "calibrates" his controls. Then, manage your input relative to that.

One code example I can suggest, tho I have no way of trying it right now is:

```
Vector2 mainCharacter;
private float cX = 0, cY = 0, speedX = 0, speedY = 0;

public void calibrate(){
    cX = Gdx.input.getAccelerometerX();
    cY = Gdx.input.getAccelerometerY();
}

public void render(float delta /** you are not using this delta **/) {
    float speedX = 0.6f * speedX + 0.4f * - ( cX - Gdx.input.getAccelerometerX());
    float speedY = 0.6f * speedY + 0.4f * - ( cY - Gdx.input.getAccelerometerY());
    mainCharacter.move(speedX, speedY);
}

```

Hope this helps, Good luck!
> 1 votes

---
Tags: android, libgdx, accelerometer
---


# Question
Title: Why are dungeons so often created subtractively rather than additively?
I'm having difficult deciding on how to procedurally generate a dungeon floor. The way I've been doing it so far is like so:

* Populate list of Rooms with random height and width.
* Place first room in list at (0, 0).
* Add room to a temporary list of rooms that have been successfully placed.
* Place next room adjacent to a room randomly chosen from the aforementioned temporary list
* Keep repeating previous step until room is successfully placed then move onto the next room.
* Repeat the two previous steps until all rooms have been placed.

After that the doorways between the rooms are created and various steps are taken to assure collision is working properly but my question is this: **Why does it appear to be common practice to first create a large area of cells that all are 'filled in' and to then 'carve out' rooms and corridors rather than to generate dungeons my way?** I'm not saying my way is better, I would be happy for someone to tell me what I'm doing wrong and why I should be doing it differently. I just find my way easier for managing the various rooms and cells within my dungeon. It also means I don't have a bunch of 'useless' cells on the other side of the dungeon walls doing nothing but hogging processing power - that's something I never understood.

I just want to a way of generating a dungeon which balances efficiency and design.

# Answer
> 3 votes
If it's easy for you, keep to it. No one says you have to do it a certain way, or that yours is wrong.

The reason it's typically done this way - subtractively or as you aptly put it, "carved" - is most likely due to the influence of roguelikes, which were arguably some of the first games to generate dungeons. In roguelikes the player can tunnel anywhere within the level's rectangular space, so every cell, even if not initially walkable, is recorded as a tile in the map, in case it becomes walkable later. Thus, tiles may as well all start out as closed spaces with the potential to be opened.

Another genre very often associated with tilemaps is the RTS, where most ground is open by default, and in which it thus makes sense to simply generate the map as all open tiles. Overland RPGs are similar in this regard. So this is certainly another influence on the typical approach.

Your approach better suits a game in an indoor space where no dynamic tunnelling will occur, i.e. once the level's rooms have been created, they will always remain the same. Obviously then we can have various very small 2D arrays each representing a room's tiles, and these can be connected in graph-fashion. This is far more memory-efficient, but again, tunnelling in the large spaces between room bounds is, if not impossible, then harder to achieve (at least, you would need to create new nodes in your graph of rooms, and allocation may not be intuitive since you don't know how wide/high the room in question will ultimately be). Memory is hardly an issue for most game levels, given the low cost per tile and the memory we have available these days (gigabytes).

This is informative in terms of the sheer number of different approaches to maze generation.

---
Tags: xna, procedural-generation, level-design, roguelikes
---


# Question
Title: Android canvas.drawColor throws a null object reference
I have two nearly identical methods, the first to draw a splash screen while assets are loading, and the second to draw all of the assets to the screen. The first throws a NullPointerException on this line:

```
canvas.drawColor(Color.argb(255, 0, 0, 0));

```

Here is my error:

> `Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference`
> `10-19 21:54:56.042 18973-18973/? E/AndroidRuntime: at com.xyz.123.GameView.drawSplash(GameView.java:76)`

Here is my code in full:

```
package com.xyz.123;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements Runnable {
    volatile boolean playing;
    Thread gameThread = null;
    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder holder;
    private int screenWidth;
    private int screenHeight;
    private Background1ResourceList background1ResourceList;
    private Background background1;
    private Background background2;
    private Background background3;
    private Context context;
    private SplashScreen splashScreen;

    public GameView(Context context, int screenWidth, int screenHeight) {

        super(context);

        this.context = context;

        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;

        // Initialize our drawing objects
        holder = getHolder();
        paint = new Paint();

        splashScreen = new SplashScreen(context, screenWidth, screenHeight);
        drawSplash();

        background1ResourceList = new Background1ResourceList();

        background1 = new Background(context,         background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.00f, 0.50f);
        background2 = new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.33f, 0.80f);
        background3 = new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.66f, 1.00f);
    }

    @Override
    public void run() {
        while (playing) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        background1.update();
        background2.update();
        background3.update();
    }

    private synchronized void drawSplash() {
        if (holder.getSurface().isValid()) {
        //First we lock the area of memory we will be drawing to
        holder.getSurface();
        canvas = holder.lockCanvas();
        // rub out the last frame
        canvas.drawColor(Color.argb(255, 0, 0, 0));
        // draw the backgrounds
        splashScreen.draw(canvas, paint);
        // unlock and draw the scene
        holder.unlockCanvasAndPost(canvas);
        } else {
            System.out.println("surface not valid");
        }
    }

    private synchronized void draw() {
        if (holder.getSurface().isValid()) {
            //First we lock the area of memory we will be drawing to
            canvas = holder.lockCanvas();
            // rub out the last frame
            canvas.drawColor(Color.argb(255, 0, 0, 0));
            // draw the backgrounds
            background1.draw(canvas, paint);
            background2.draw(canvas, paint);
            background3.draw(canvas, paint);
            holder.unlockCanvasAndPost(canvas);
        }
    }

    public void pause() {
        playing = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {

        }
    }

    public void resume() {
        playing = true;
        gameThread = new Thread(this);
        gameThread.start();
    }
}

```

# Answer
The reason the canvas is null is because I'm trying to get a canvas from within the constructor of the GameView (which is a surface view).

I moved the call to drawSplash method into the run method immediately before the game loop and it works perfectly.
> 1 votes

---
Tags: android, html-canvas
---