# Question
Title: Time series for creating new events in a PVP game
This is more like a mathematical problem, but I guess this is the best place to ask it.

I am working on a PVP concept and I have the following problem. There is a "battle" between two players that both have set their moves before the match starts. So, during the battle, they just watch the screen and text describing the events.

This battle takes 30 min and attacking/defending text events are appearing during this time. In average, I have about 5 main events and 3 secondary events. When the battle start, the code is aware of the number of main events, but not the secondary. They are calculated on the fly.

The process is like,

```
newEventTime = previousEventTime + formulaForRandomTimeInterval

```

What I try to do is to build that formula and avoid having big empty time gaps on the battle and also avoid having a lot of them in a small period.

Also, I want to have slightly more events as the time pass to increase the interest.

Was thinking something such as:

```
formulaForRandomTimeInterval = (battle_time*2/main_events)*random(0,1)

```

where `battle_time = 30` and `main_events` the number for that battle.

Any idea for a better solution?

**Edit**

Sorry for the confusion. Here are a couple of more details about it.

An example of events:

1. At 3' Player A attacked and made 45 damage. (Main event)
2. At 8' Player B attacked with a sword and made 110 damage. (Main event)
3. At 12' the weather changed and started raining. Both players had issues with the mud. (Secondary event)
4. At 19' Player A made a move but player B dodged the attack. (Main event) ... ...

There is another part of the code that decide which event will be the next and what exactly would be. The battle will be over only when the main events are finished. As I said, each battle has different number of main events of average 5, but the code know this number as the battle starts. But doesn't know the number of secondary events which are created by random.

So, when the code does the loop on the events and decide the type of the next event, the time code is called to decide in what minute it will be appeared.

# Answer
Before we start: Why does the code not know the random events beforehand? Without interaction, couldn't you just as well calculate them in advance without any difference in the player's experience? And if their effects affect the battle, how can you know the number of main events without knowing the impact of random events? Ah, I probably don't need that part of the picture, so let's get started with the mathing.

---

This is a math question at first glance, but there's more to it than that. I would factor the nature of events into determining their frequency.

What I gather from your examples is that there are basically turn-based actions and random (environmental) effects. These two are different concepts that depend on different factors, so the player will have different expectations as to when they happen. There is also a different impact of the effects based on when they happen.

The frequency of turn-based actions should be related to the abilities of the character. It would make little sense for the same sword attack to take twice as long as usual because it is starting to rain, and then take the normal time while it's still raining. The battle speeding up bit by bit makes sense, and reflects the growing desperation and determination to win before running out of strength or getting killed yourself. Speeding the battle up means we have higher action density towards the end of the battle.

Random events happen, well, randomly. The player will have very few expectations here, except maybe a reasonable distance between events like weather changes. But nobody would be surprised if, a minute after it starts raining, a wild boar charges out of the nearby woods. This means you have a lot more freedom with the random events. However, in order to affect the battle, they would have to happen early.

This is quite fortunate. We can have random events happen mostly in the first half of the battle, while the constant acceleration pushes attacks into the second half. In other words, accelerating the turn-based actions opens a time window for the random events.

---

My solution would be to implement two timelines:

Turn-based actions happen in a mostly uniform fashion, each action up to 10-20% faster than the previous. That allows you to add up the factors and scale them against the total.

Random events mostly happen in the larger time spans at the beginning of the battle. You can time them to be 1/3 to 2/3 of the way to the next event for a randomized but even distribution. Sometimes they do happen between the shorter turns at the end, but I'd keep the probability for that low, maybe by scaling effect probability with duration of the next action.

I would avoid using the loop to calculate time, but rather calculate all beforehand and just check the system time to see if it's time to display the next event. That saves cpu usage if the game is running on a device that is multitasking, even if it's just a few cycles.

---

Let's start with the turn-based actions:

> Calculate duration modifiers, get each by randomly modifying the previous one
> Using ~20% and 6 actions for a more visible effect here
> Example random duration modifiers of 6 turn-based actions:
>
> D0=0, D1=1, D2=0.8, D3=0.72, D4=0.67, D5=0.55
>
> calculate the sum of all duration modifiers up to the
> current modifier to get the timestamp modifier
>
> T0=0, T1=1, T2=1.8, T3=2.52, T4=3.19, T5=3.74
>
> Scaling towards the desired total time:
>
> Total time is proportional to the last modifier.
> Divide total time by it to get the time scale factor
>
> 1800sec/3.74 = 481,28sec (whatever precision you need)
>
> Multiply each time modifier with the time factor to get the time its event happens
>
> Ex.: T3 = 2.52 x 481,28 = 1212sec = Minute 20 (:12sec)

Each of these sets of calculations fit nicely into a for loop handling an array.

Now to designate a time to the random events. We shift the probability towards the beginning of the battle to balance against acceleration. I'll show two samples for comparison

> Do this whenever you display a turn-based action :
>
> Get the duration modifier of the next action
>
> T1.next = D2 = 0.8
> T4.next = D5 = 0.55
>
> Square the number to shift the probability to the early battle. These are your probability modifiers.
>
> P1 = 0.8^2 = 0.64 chance for random event to occur between T1 and T2
> P4 = 0.55^2 = 0.3025 chance for random event to occur between T4 and T5
>
> ...maybe use 3rd or higher power to increase the difference
> and make late effects something 0.1-ish...
>
> In case of a random event,
> place it halfway to the next turn-based action, +/- 1/3.

Disclaimer: This is by no means balanced, but demonstrates a way to push events between others while maintaining a relative scale of time between events and might be a starting point for your own design.
> 1 votes

# Answer
I share the skepticism @Estharon expresses about whether players will enjoy a 30-minute non-interactive battle, but I'll answer as if it's a given that these will be interesting events.

Unless there's a compelling reason for this to take exactly 30 minutes, I would make a sequence of smaller fixed or randomized decisions (balanced around a target duration) as the battle plays out rather than trying to pick times before the battle starts without complete knowledge of the events or of how slow/fast the player reads.

Consider a few basic mechanics along these lines:

* The battle has a variable **current\_intensity**
* Each individual event has its own (appropriate) fixed **intensity** and **effect\_on\_battle\_intensity**
* Each event could have a set **duration** and **message frequency**, though I would probably just have a simple format for writing out template lines and a delay before the next message (in which case **duration** is just a sum). The latter would let you mix messages of differing lengths a little more effectively, while the former would require writing messages that stay within a smaller range of what the player can keep up with.
* Rather than try to select events more frequently towards the end of the battle, you select more intense (dense/verbose/dramatic) events as the intensity of the fight rises
* Skew either the event pool or the event selector towards events that increase intensity (probably just a 10-35% chance or so of an intensity-reducing event)
* When one event ends, explicitly choose a tolerable delay before starting the next event (random, fixed, or based on the duration of the ending event)
* The battle has a fixed or random **terminal intensity** that, once exceeded, will select an event from a pool of battle-terminating events

This would let you cobble together a varied action sequence from well-planned events with reasonably small interruptions. The sequence can have a sense of rising action to some terminal event. It also builds in several levers that you can play with to make the experience more variable. If the players don't have any leveling mechanism, you could just have 5 or 10 intensity levels and start the battle at 1. If players can level up, the start and terminal intensities can depend on player levels.
> 3 votes

---
Tags: mathematics, text-based, timestep
---


title: Changing tag on collision

text:
# Question
Title: Changing tag on collision
I'm trying to switch the tag on my Player to something else when a collision between two unrelated objects happens, and then switch the tag of another object to Player, so my camera script will follow it.

**How do I detect a collision between two objects that do not have my script attached to them?**

`void OnCollisionEnter(Collision col)` only detects collision on the object that the script is assigned to, so I can't use that. Either I need to know how to detect a unrelated collision in a script, or I need to know how to change the tag of an object that does not contain the script.

This script is on my player, whom does not collide with anything:

```
void OnCollisionEnter (Collision col)
{
    if (col.gameObject.name == "triggerCube")
    {
        Debug.Log ("HIT");
    }
    else
    {
        Debug.Log ("HIT2");
    }
}

```

The \`Debug.Log("HIT") does not show when the objects collide. This script is on the object "triggerCube":

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class EndPoint : MonoBehaviour
{
    public Text textWin;

    private Vector3 offset;

    void OnCollisionEnter (Collision col)
    {
        if (col.gameObject.name == "triggerCube")
        {
            Debug.Log ("HIT SOMETHING");
            setWinText ();
        }
    }

    void setWinText ()
    {
        textWin.text = "LMAO";
    }
}

```

# Answer
> 1 votes
You can't detect a collision between two objects if you do not add a script to one of them. You have to add another script to the colliding objects, and then let your EndPoint script know about that collision through a function call.

# Answer
> 1 votes
As stated in the other answers, collision is only initially being handled between the two game objects that are colliding. You need to have a script on one of the two objects involved in the collision, and have it relay information back to the player, somehow.

## Potential problems with same-named objects colliding

In your example, you have a script that is *on* an object named "`triggerCube`". You *also* check to see if the *other*`col.name == "triggerCube"`, suggesting that both objects are named "`triggerCube`".

It is important that you are aware that ***both*** cubes will trigger a collision. This means that if both cubes have the `EndPoint` script, they will each run their own version of `OnCollisionEnter`, where they will each see the opposite `triggerCube` and determine that `(col.name == "triggerCube") == true`.

'Why is this important', you might ask? Well, it means that your logic will be run *twice*. Under some logic, this won't *appear* to mess things up; but you might have some fatal errors, as a result. You could also have situations where the "`Player`" tag jumps an extra game object, depending how you have things set up, as both `triggerCube` objects detect a collision and *individually* instruct the player to 'hop objects'.

I will *assume* only *one* of the `triggerCube` objects contains the `EndPoint` script, which allows quick assurance that the logic will only process *once*. You may also want to look at an alternate question, "Check which object triggered another".

## Alerting the `Player` object to collision

Ultimately, you need to be able to identify the `Player` script, to push action to the player when your two `triggerCube` objects collide. You can do this several ways, each of which has their advantages and disadvantages. We will *assume* that the script attached to your player is called *Player*.

Here are three easy ways to set up your reference:

* **Use Unity Editor:** If your only making the jump once, this is the quickest and most reliable way to go.
* **Use a static script:** If your only keeping one instance of the player, this might be the quickest way to go. Beware: If you do not properly *ensure* that you only have *one* `Player`, your going to have a bad time.
* **Find the reference on the fly with tags:** If you only have one `Player` tag at a time, this might be the more reliable way to go. Than again, if you have a lot of objects in your scene, you might find that this method is slow to work itself out.

### Passing the reference via Unity Editor

Having a public reference allows you to manually set the reference using drag and drop, in the Unity Editor.

This is a good way to test out certain functionality, while ensuring correct reference. This is also a good way to go when the reference is some what *static* \- that is, *if the script should not move from that game object*, your reference should always work properly. This is also, arguably, the easiest way.

If you have to perform this sort of action *again*, i.e. it is not a 'one-time only' event, this is probably not the best solution. If you *still* go this way, you will still have to ensure that the reference is properly set up again, when you move to the next 'player object'. Since your now in-game, you will have to reset the reference *without* the Unity Editor, so your better off just using one of the more adaptable solutions from the start.

```
public class EndPoint : MonoBehaviour
{
    public Player player;

    void OnCollisionEnter(Collision other)
    {
        if(other.gameObject.name == "triggerCube")
        {
            player.NextPlayer();
        }
    }
}

public class Player : MonoBehaviour
{
    public void NextPlayer()
    {
        // Move tag to next object;
    }
}

```

### Keeping a `static` reference to `Player`

Having a `static` reference allows you to guarantee access to your script, but you should remember that to be static, a script can not have instanced variations in play. While you are not hard-bound by this constraint in *using* `static`, if you do not follow the logic, bad things will happen.

You could consider attaching the script to your new 'player object' with each `NextPlayer()`, if you need to move players more than once. ***If your logic insists that multiple `Player` scripts be at play at the same time, this will not work for you.*** If you have multiple `Player` scripts, with only one at play at a single time, you still need to make *absolute* sure that `Player.me` references the *active* version of your `Player` script. Even with precision, that could be tricky.

```
public class Player : MoboBehaviour()
{
    public static Player me; // cheeky self-reference

    void Start()
    {
        me = this;           // set up the self-reference
    }

    public void NextPlayer()
    {
        // Move tag to next object;
        // Attach this script to the next object;
        // That way, this static script can be kept,
        // but it still references the next object with this.gameObject
    }
}

public class EndPoint : MonoBehaviour
{
    void OnCollisionEnter(Collision other)
    {
        if(other.gameObject.name == "triggerCube")
        {
            Player.me.NextPlayer();
        }
    }
}

```

### Finding `Player` on the fly with tags

Another option you have is to locate the player using the same tag you wish to change.

This solution is more likely to work on the fly, in a variety of circumstances. That said, we are relying on checking all objects for the `Player` tag; while the scenario you describe seems to imply only one `Player` tag will be in use (so we are not worried about finding the wrong object), you have to keep aware of how many game objects are currently in your scene. As your logic has to sort through more objects to find the player, it will take longer to complete its operation.

```
public class EndPoint : MonoBehaviour
{
    Player player;

    void OnCollisionEnter(Collision other)
    {
        if(other.gameObject.name == "triggerCube")
        {
            FindPlayer();
            Player.NextPlayer();
        }
    }

    void FindPlayer()
    {
        GameObject.FindWithTag("Player");
    }
}

public class Player : MonoBehaviour
{
    public void NextPlayer()
    {
        // Move tag to next object;
    }
}

```

## Moving the "`Player`" tag

Now that's all sorted out, changing the tags should be quite easy. Simply calling `gameObject.tag =` in a script should give you the ability to change its tag. That said, you ***must*** ensure you set a tag that has previously been set in the Tags & Layers Manager.

If it was not already obvious, you will have to retrieve a reference to your 'new player object', just as you had for your player. *You should be able to do this in effectively the same way as you would to identify the initial 'player object'.*

You may consider using a different method to that which you used for `Player`. Keep in mind that since you may not be calling any real script logic on the other side, yet, you may not have an actual *script* on the other side. You can store a reference to the *direct game object* with `GameObject nextPlayerObject`, and work your way from there.

# Answer
> 0 votes
As things are right now, only your player can detect collisions. For this to happen your player must have a collider attached, and be sure the `IsTrigger` checkbox is unchecked. If you want to make it react to `IsTrigger` than you should change your `OnCollisionEnter()` to `OnTriggerEnter()`.

Collisions can only be detected if at least one of the colliding objects has a call to `OnCollisionEnter()` or `OnTriggerEnter()`, depending on if you want the collider to react to collisions or triggers, and obviously both colliding objects must have a collider attached.

For further detail on understanding how to properly handle collision detection among your objects, please see this question.

---
Tags: unity, c#, collision-detection
---


# Question
Title: Unity2D: How to destroy spawned object once it exit out of camera's view?
I'm trying to destroy spawned objects once it exit out of camera view automatically/straight away. You see I'm trying to make a flappy brids type of game but things also comes in from the bottom and if they get a really high score then things will be spawned in from above and from the left side. So, so far this is what my game looks like (I'm still working on it). However I'm having problems with deleting spawned objects once it exit out of camera's view, I tried all sorts of things like:

```
private var hasAppeared : boolean;

function Start ()
 {
hasAppeared = false;
}

function Update()
{

if (GetComponent.<Renderer>().isVisible)
{
    hasAppeared = true;
}

if (hasAppeared)
{
    if (!GetComponent.<Renderer>().isVisible)
        {
            Destroy(gameObject);
        }
    }

}

```

But with this script, it doesn't destroy the game object quickly enough that and only some of them is being deleted. I also tried this method:

```
     public void OnBecameInvisible() {
        Destroy(gameObject);
      }

```

But not all of them is being deleted as well and it also takes a long time for any of my game objects to be destroyed. My last result was this script, it destroys the game object straight away once it exit out of the camera's view (which is what I want) but only these sides works where as the other's don't, I think it destroys my enemies (spawned objects) before it has even entered the camera's view. How do I get the script to work on this side? This is my script:

```
void Update ()
{
    DestroyAllEnemy ();
}

public void DestroyAllEnemy()
{
    GameObject[] enemies = GameObject.FindGameObjectsWithTag ("enemy");
    if ((enemies.Length > 0) && (camera != null)) {
        for (int i = (enemies.Length - 1); i >= 0; i--) {
            // just a precaution
            if ((enemies [i] != null) && ((camera.WorldToViewportPoint (enemies [i].transform.position).x > 1.03f) ||
                (enemies [i].transform.position.y < -6f)))
            {
                Destroy (enemies [i]);
            }
        }
    }
}

```

Thank you :).

# Answer
> 2 votes
`OnBecameVisible` and its counterpart has a few gotchas.

1. It works only if the gameobject has geometry.
2. The editor view also triggers these events.

You might want to look at the CullingGroup API if you want to avoid these issues.

# Answer
> 0 votes
Don't allow removal until the object has been seen at least once.

```
bool readyToRemove = false;

void OnBecameVisible() {
    readyToRemove = true;
}

```

Then use one of your other methods to remove, for example:

```
public void OnBecameInvisible() {
    if(readyToRemove)
        Destroy(gameObject);
}

```

As an aside, I'd suggest you look into recycling the objects with object pooling.

---
Tags: unity, camera, spawning
---


title: Game Website Wrapper

text:
# Question
Title: Game Website Wrapper
I am looking to make a simple program (in any language) then when you run the .exe the only thing it does is display a website (the whole website is my game) without any navigation buttons as they are integrated into the pages.

# Answer
Why not just use WinForms and a WebBrowser-Form? See Browser class in WinForms for reference. WinForms is a Framework for creating Windows programs with C#. Basically you download and install Visual Studio, create a new WinForms project. There you've got a designer tool to drag and drop elements onto a basic window. In your case you would drag a browser element onto the form and with `browser.Navigate(URL)` you can show your website. Note, that you can also show a website/html document that is locally on your computer or included with your program. You can then compile and release your program as a .exe.

This is also very common on other systems than windows, maybe you want to read into the Android WebView for example as well.
> 1 votes

---
Tags: software-engineering, web, webapp
---


title: Finding a tile number in a grid system

text:
# Question
Title: Finding a tile number in a grid system
Hi I am trying to find the Tile number of a grid of tiles based on the Z and X coordinates.

Where the Z and X axis are potentially infinite in either direction how can i get the number of the tile, based on the Z and X coordinates.

Sorry for the crude drawing

# Answer
> 5 votes
The only way I know of, or at least can think of right now, is the following:

Prerequisites:

1. You need to know the width and height of your grid
2. the tile numbers must increase successively, so like you have in your drawing atm

If you got those 2 things, then you would use the formula

```
tile number = height * "index in width direction" + "index in height direction"

```

Now I have defined this very very general in sorts, since it is very dependant on the orientation of your grid and in which direction the rid grows. So to be more specific here a small, very artistic paint illustration of the situation you have above :)

The blue numbers are the indices in either direction. In your specific case, with z going up and x to the right, where z fills up first, the idea would: be

* use the x index to see "how many columns are filled" (since when you are at x\_index = 1, that means x\_index = 0 is filled with "height" amount of cells)
* Add to that the z:index, since that is the amount of cells in the partially filled column not counted yet

Don't forget though to make sure you are using the correct values, since as mentioned before these grids can be different and thus examples may not always apply to your situation directly.

Not sure if this will answer your question to your satisfaction, since I do not know if the prerequisites apply in your case.

Using this method you can for example also treat a "normal" one dimensional array as a 2 dimensional one, since you can always calculate which cell in the one dimensional array you need to access via the x and y indices (useful for i.e. graphics programming in some areas)

# Answer
> 2 votes
Throzen's answer may have answered Josh's needs, but it doesn't answer the question as it stands (*infinite* grid, no grid height nor width available) so I'll leave this answer here if anyone is interested.

One can try a diagonal or a snail tiling. Which one you should use depends on what is meant by:

> infinite in either direction

---

## 1) If you mean X axis is \[0, +Inf) and Y-axis is also \[0, +Inf)

Then use a diagonal tiling, like so:

```
9
5 8
2 4 7
0 1 3 6 ...

```

I'll leave it up to you to figure out how to make a pair (i, j) into a tile number, but it is rather simple. The reverse function is also possible, but (slightly) more complex.

## 2) If you mean X axis is (-Inf, +Inf) and Y-axis is also (-Inf, +Inf)

Then you can use a "snail" tiling like so:

```
      .
4 3 2 .
5 0 1 .
6 7 8 9

```

Again, there is a way to make a pair (i, j) into a tile number. The reverse function is also possible.

---

These answers let you number a tile at arbitrary position, **without prior knowledge of the grid size**. This comes with the drawback of an increased (though manageable) computing cost.

---
Tags: mathematics, coordinates
---


# Question
Title: How would I go about generating a star map?
Im trying to generate a star map.

My try would be:

1. Have a width and height for the map.
2. Place points (stars) randomly across the area of width and height.

A simple approach, but it has the problem of randomly placing stars extremely close to each other.

To solve this problem, one approach would be to have a minimum distance and when generating a star, you compare the distance from the new star to every generated star and if its below minimum distance, you generate a new one, but I dont know if thats efficient. Any tips?

# Answer
> 16 votes
A Poisson-Disk sampling distribution will allow you to select random points a minimum distance apart & Bridson's algorithm can efficiently solve the problem in O(n) - fast enough for real time provided your star count doesn't get too huge.

Bridson's algorithm divides the output region into a grid of cells sized relative to the minimum allowable distance, such that only one point can appear in each cell. Then, when you consider adding a new point, you only need to check a disk shaped collection of neighboring cells as opposed to the entire list of points. For instance, consider the following image:

When checking to see if the candidate blue dot is too close to existing dots, you don't need to check it against every existing dot. Instead you can restrict the search to the dots in the neighboring cells (which you can find quickly using a lookup table). Mike Bostock has a nice animation showing the algorithm in progress.

The standard implementation is only concerned with a fixed minimal distance between points. Herman Tulleken's Poisson Disk sampling article (includes source code) covers an adaptation for varying the minimum distance at different parts the image; basically like a dithering algorithm. Using perlin noise / simplex noise as shown in the article clouds might give a more natural looking star map. For example, I used the image on the left to generate the right:

To do this, when considering a candidate point, I first check the value of input image, which yields a value from 0 to 1. I then scale this to my desired min & max distance between points; in this case I selected 5 & 20 pixels. So when placing a point in the dark regions, my stars can be as close as 5 pixels to each other & when placing stars in the light regions, they can be up to 20 pixels apart.

It's worth noting that Bridson's speed up doesn't exactly work with variable distance sampling because the output points aren't using a uniform minimum distance. However you can still use a the output grid to reduce the searching. A smaller the grid results in a quicker the search for nearest neighbors at the expense of increased memory for a larger lookup table.

# Answer
> 1 votes
One very naive but simple solution would be to simply always jump the "minimum" distance, and then append a random amount on top of that. This means stars will never get too buddy buddy, and you'll at least get a bit of deviation.

e.g

```
for (int x = 0; x < MAX_WIDTH; x+= MIN_SEPERATION_X)
{
  x += generateRandom();

  for (int y = 0; y < MAX_HEIGHT; y+= MIN_SEPERATION_Y)
  {
    y += generateRandom();

    if (x < MAX_WIDTH && y < MAX_HEIGHT)
    {
      image[x + y * width] = STAR;
    }
  }
}

```

(Inserting your favourite random number generation function)

# Answer
> 0 votes
If you know the X Y Z size of your play space you could pick a random spot in that space

and then do a SphereCast to check if there is anything too close already.

```
//pseudo code

SpawnStar(){
 Vector3 spot = new vector3(random(0,world size),random(0,world size,random(0,world size)

  while(true){
  SphereCast(spot, radius)
   if(hit something){
      spot = get new random spot
    }else{
     SpawnStar();
     brake;
    }
  }
}

```

Problem with this is that it probably wont be very good for real time, however for pre generated it's fine and pretty quick.

---
Tags: procedural-generation
---


title: Unity Online Multiplayer

text:
# Question
Title: Unity Online Multiplayer
I have searched this on the internet, but I didn't get any clear answers. My question is - Can I implement an online multiplayer functionality in Unity personal edition? Also without spending any money.

# Answer
According to the main Unity website, yes; you can implement free online multiplayer functionality in the personal edition, with up to 20 concurrent players.
> 4 votes

# Answer
In addition to the multiplayer service that Unity itself offers, you can also create your own, removing the limitations of the free service. Depending on what kind of a system you go with, you can create your own master server where the actual game servers announce themselves at and where the actual game client retrieves a list of servers. This would require you to have extensive knowledge about networking code in general and would be a bigger task then implementing the default service.
> 1 votes

---
Tags: unity, multiplayer, online
---


# Question
Title: How can I get a Box Collider's "corners" (vertices) positions?
I attached a Box Collider to a object, which has not the center as its pivot. Now I need the 8 corner points.

Right now I can only get the points in a unrotated state. But whenever I rotate the Object (which rotates in the center of the boxCollider) - everything gets messed up, because the rotation alters the gameObject-Position.

EDIT2: Solution

```
public Vector3[] GetColliderVertexPositions (GameObject obj)
{
    BoxCollider b = obj.GetComponent<BoxCollider>(); //retrieves the Box Collider of the GameObject called obj
    Vector3[] vertices = new Vector3[8];
    vertices[0] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z) * 0.5f);
    vertices[1] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z) * 0.5f);
    vertices[2] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z) * 0.5f);
    vertices[3] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z) * 0.5f);
    vertices[4] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z) * 0.5f);
    vertices[5] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z) * 0.5f);
    vertices[6] = obj.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z) * 0.5f);
    vertices[7] = obj.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z) * 0.5f);

    return vertices;
}

```

Found that:

Most efficient way to get the world position of the 8 vertexes of a Box Collider (C#)

# Answer
Collider.bounds is an AABB (Axis-Aligned Bounding Box). An AABB is always parallel to the world axes. This figure that I just drew may help with the concept:

Therefore, it does not have the corners of your box collider in local coordinates. Rotating it creates a weird situation.

If you are happy with AABB's, then use its coordinates without rotating. If you really need the corners of your box collider, you're going to have to use `BoxCollider.offset` and `BoxCollider.size` to calculate the local coordinates of the corners and then do `Transform.TransformPoint()` to get their world coordinates.

**Please note:** When trying to find coordinates within a `BoxCollider2D`, one must now use `BoxCollider2D.offset` instead of `BoxCollider2D.center`, as the latter is deprecated. The answer is updated to reflect this change.
> 5 votes

---
Tags: unity, bounding-boxes
---


title: Collision detection errors

text:
# Question
Title: Collision detection errors
I have a list of game objects I'm trying to check collision against. My collision system is using code ive seen posted here before, but I'm not sure where I'm going wrong here.

```
 private bool Intersects(Rectangle player, Rectangle other, CollisionDirection direction, out Vector2 depth)
    {
        if (direction == CollisionDirection.Vertical)
        {
            depth = new Vector2(0, GetVerticalIntersectionDepth(player, other));
        }
        else
            depth = new Vector2(GetHorizontalIntersectionDepth(player, other));

        return depth.Y != 0 || depth.X != 0;
    }

    public float GetHorizontalIntersectionDepth(Rectangle rectA, Rectangle rectB)
    {
        float halfWidthA = rectA.Width / 2;
        float halfWidthB = rectB.Width / 2;

        float centerA = rectA.Left + halfWidthA;
        float centerB = rectB.Left + halfWidthB;

        float distanceX = centerA - centerB;
        float minDistanceX = halfWidthA + halfWidthB;

        if (Math.Abs(distanceX) >= minDistanceX)
            return 0;

        return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
    }

    public float GetVerticalIntersectionDepth(Rectangle rectA, Rectangle rectB)
    {
        float halfWidthA = rectA.Height / 2;
        float halfWidthB = rectB.Height / 2;

        float centerA = rectA.Top + halfWidthA;
        float centerB = rectB.Top + halfWidthB;

        float distanceX = centerA - centerB;
        float minDistanceX = halfWidthA + halfWidthB;

        if (Math.Abs(distanceX) >= minDistanceX)
            return 0;

        return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
    }

    private void CheckCollisions(CollisionDirection direction, List<GameObject> objects)
    {
        foreach(GameObject obj in objects)
        {
            Vector2 depth;
            if(Intersects(CollisionRectangle, obj.g_CollisionRectangle, direction, out depth))
            {
                g_WorldPosition += depth;
                Debug.WriteLine("true");
                if (direction == CollisionDirection.Horizontal)
                    g_Velocity.Y = 0;
                else
                    g_Velocity.X = 0;
            }
        }
    }

```

And in my update method I do this.

```
....
if(ks.IsKeyDown(Keys.S))
        {
            g_WorldPosition.Y += 10f;
            playerFacing = Direction.DOWN;
            CheckCollisions(CollisionDirection.Vertical, objectList);
        }
        if(ks.IsKeyDown(Keys.A))
        {
            g_WorldPosition.X -= 10f;
            playerFacing = Direction.LEFT;
            CheckCollisions(CollisionDirection.Horizontal, objectList);
        }
...

```

In the CheckCollision method the Debug line is writing true to the output even when i'm not colliding with anything. I know the g\_CollisionRectangle is being set correctly because I have lines being drawn around the outside of each collidable object.

What happens is my player kinda moves sporadically because I'm getting collisions in places where I shouldnt. Can anyone see where I'm going wrong here? I realize that g\_Velocity is not being used in my update method, but I don't think that it should effect what is happening at this point. From what I can tell, my GetVertical and GetHorizontal methods are wrong somewhere because of the Debug line in the CheckCollision method.

# Answer
> 1 votes
Make sure you don't check collision against itself.

It is not entirely obvious from the code you posted, but if the player is also part of `objectlist` it will be part of the collision code and it checks against itself (since it occupies the same space obviously) resulting in 'true'.

Alter your code `CheckCollisions` like this:

```
foreach(GameObject obj in objects)
    {
        if(obj==this)
        {
            continue; // Don't check for collisions against self.
        }

      Vector2 depth;
     ... //do rectangle intersection etc.
    }

```

That is, I assume the object is included in the collection you pass to this method.

---
Tags: c#
---


title: Unity OnCollision() not working

text:
# Question
Title: Unity OnCollision() not working
Seem to have exhausted google looking for an answer to a VERY bullet simple code that should work.

```
void onCollisionEnter(Collision col) {
    print ("hit " + col.gameObject.name);
    Destroy (gameObject);
    }

```

Bullet object has the above script, SphereCollider (radius a lot bigger than object), RigidBody, not a trigger, not kinematic, is travelling slow. All checked during runtime.

When it hits a wall (Box collider), it just bounces off but no collisionEnter code is ran.

Debug console bubble is on.

# Answer
> 1 votes
While you are trying to call `onCollisionEnter()`, MonoBehaviour uses the function `OnCollisionEnter()`.

The difference is quite enormous, on the technical side of things. Being a function, the *first* letter should be a capital. By being lower case, your creating an entirely *different* function, that does not overload the original collision function your trying to call from MonoBehaviour.

To *clarify*, we are not *overloading* a method from `MonoBehaviour`, in the traditional sense. You should ***not*** use the `override` keyword, as this will report "no suitable method found to override".

---
Tags: unity, collision-detection
---


# Question
Title: How to disable collider2D when another gameobject is on top of it
Each black colored square has a `BoxCollider2D`. How can I disable the collider after I put another game object on top of it?

Here is the sample output:

# Answer
**Note: most of what I discuss, below, is general to collision. While you can reference a 2D collider as a generic `Collider`, most other actions require *direct* reference to the *type* of collider you are using, more specifically whether it is for 2D or 3D. This includes the function call, and assurance that you are using the correct `Rigidbody`|`Rigidbody2D` and `Physics`|`Physics2D`, where applicable.**

Colliders are a separate component, even when attached to a game object, so disabling them on collision is actually quite easy.

To disable the collider from a script attached to the same object, you can simply use

```
void OnCollisionEnter2D(Collision2D collision)
{
    GetComponent<Collider>().enabled = false;
}

```

This is the same as creating a reference to the collider on the other game object with `Collider collider = GetComponent<Collider>()` and disabling it with `collider.SetActive(false)`, but quicker, given that we do not need to use the reference `collider` after we initially disable it.

If your script is on the *other* object, we only need to accommodate the fact that we are looking for the collider on the *other* object with `collision.other.gameObject.GetComponent<Collider>()`.

If your script ends up invoking `OnTriggerEnter(Collider other)`, instead, you can reference the *other* collider directly with `other`, or access the `GameObject` with `other.gameObject`. Note that `OnTrigger` functions directly pass a `Collider`, as these instances only need to work with *what* was hit, and does not need the extra information passed through a `Collision` object.

### `Collider` is compatible with all types of colliders

Note that `Collider` is an object that represents colliders, and as such, all colliders inherit from it. That means that this reference will work regardless of whether you are using a `BoxCollider`, a `BoxCollider2D`, a `MeshCollider` or any other variation that suits your particular needs.

### Handling multiple colliders on the same game object

When things get more complicated, your game object may contain several colliders1. You can use `GetComponents<Collider>` to return a list of *all* colliders on the game object, and iterate through them to disable each one.

### Use tags to identify what it is your hitting

You may find that there are certain situations where your object collides with another object, but not the object you wish to trigger the 'disable collider' logic on. You can set tags on objects, and check if `other.tag` matches the same tag you use on the objects you intend to trigger the specific action. In the case where only the "square" should cause the collider to disable, you would ensure the object correctly has the "square" tag, and use `if(other.tag == "square"){}` to encase your `collider.enabled = false` code.

1 While you can only have one `Collider` component on a single `GameObject`, you may have children attached to your game object that also contain colliders.
> 1 votes

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


# Question
Title: How to pass arguments with BungeeCord/Bukkit plugin messaging
I am trying to send a plugin message from Bukkit, to BungeeCord, but can not figure out how to send arguments. Here is the code from the Bukkit plugin, which sends the message:

```
  ByteArrayDataOutput out = ByteStreams.newDataOutput();
  out.writeUTF("BungeeCord"); out.writeUTF("Argument");

  // If you don't care about the player // Player player =
  // Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
  // Else, specify them
  Player plr =  Bukkit.getPlayerExact("spacegeek224");

  plr.sendPluginMessage(p, "BungeeCord",
  out.toByteArray());

```

Here is the code in the main class of my BungeeCord plugin:

```
@Override
    public void onEnable() {
        this.getProxy();
        ProxyServer.getInstance().getPluginManager().registerListener(this, new ChannelListener());

        this.getProxy();
        ProxyServer.getInstance().registerChannel("Return");
    }

```

And finally, here is the code for the ChannelListener:

```
package net.spacegeek224.metro.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;

public class ChannelListener implements Listener {

    @EventHandler
    public void onPluginMessage(PluginMessageEvent e) {
        if (e.getTag().equalsIgnoreCase("BungeeCord")) {
            DataInputStream in = new DataInputStream(new ByteArrayInputStream(e.getData()));
            try {
                String channel = in.readUTF(); // channel we delivered
                if(channel.equals("BungeeCord")){
                   ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()).create());

                } else {
                    ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()+":"+channel).create());

                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
    }

    public void sendToBukkit(String channel, String message, ServerInfo server) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(stream);
        try {
            out.writeUTF(channel);
            out.writeUTF(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        server.sendData("Return", stream.toByteArray());

    }
}

```

I have tried many things, including Google, and looking at what other methods are available, but have come up with nothing.

# Answer
> 0 votes
I figured it out! All I needed to do was add a `in.readUTF()` for each `out.writeUTF()` I used.

---
Tags: minecraft-modding, plugin, bukkit, messaging
---


title: Disable Ubuntu shortcuts

text:
# Question
Title: Disable Ubuntu shortcuts
On Ubuntu when capturing keyboard input with GLFW some keys like `LEFT ALT` are not passed to my window. Instead some desktop functionality is triggered like the dashboard search in case of the alt key.

How do I run a windowed game on Ubuntu, using all keys available on the keyboard, without telling the user how to turn off Ubuntu keyboard shortcuts all together at game start?

# Answer
> -1 votes
This answer should hopefully annihilate those pesky shortcuts for you:

> In System Settings \> Keyboard \> Shortcuts
>
> Find the shortcut you're trying to disable, click on it to set a new shortcut, then pressing Backspace will disable that shortcut.

As for your players, I don't know of a way to default them off. I'd advise picking different keys to circumvent the issue. Some players might not want them off anyway if they were playing the game and quickly wanted to tab out.

---
Tags: c++, glfw
---


# Question
Title: Increasing mass in ineleastic collision by orders of magnitude resultsin little change in velocity
When increasing my rocketMass from 10 to 1000 or to a 1000 or bringing my shipMass down to 1, I notice very little increase in how far the ship's final inertia is. I'm expecting that increasing from 10 to 1000 will be visibly about 100 times faster.. but it's not. If I multiply the hypotenuse at the end, that does make the bouncing incredibly faster.

Am I misunderstanding physics or is this a calculation error?

```
handleCollision(r) {
    var angle = r.r * Math.PI / 180.0;
    var rr = this.r * Math.PI / 180;

    var rocketVector = {'x' : r.power * Math.cos(angle), 'y' : r.power * Math.sin(angle)};
    var inertiaVector = {'x' : this.magnitude * Math.cos(rr), 'y' : this.magnitude * Math.sin(rr)};

    var rMass = 100;
    var shipMass = 1;

    var x = (rMass * rocketVector.x) + (shipMass * inertiaVector.x);
    var y = (rMass * rocketVector.y) + (shipMass * inertiaVector.y);
    var xDividedByMass = x / (rMass + shipMass);
    var yDividedByMass = y / (rMass + shipMass);

    var yRadians = (yDividedByMass * Math.PI / 180);
    var xRadians = (xDividedByMass * Math.PI / 180);
    var theta = Math.atan( yRadians / xRadians);

    theta = theta * 180 / Math.PI;
    console.log(theta);

    var hypotenuse = Math.sqrt((xDividedByMass * xDividedByMass) + (yDividedByMass * yDividedByMass));

    if (x < 0) {
        theta -= 180;
    }

    this.r = theta;
    if (this.r < 0) {
        this.r += 360;
    } else if (this.r > 360) {
        this.r -= 360;
    }
}

```

# Answer
> 0 votes
I am going to make some assumptions about your program. I am assuming that the rocket is being fired at the ship and then is either destroyed, or becomes stationary.

If this is the case then your problem is occurring due to these lines,

```
  var xDividedByMass = x / (rMass + shipMass);
  var yDividedByMass = y / (rMass + shipMass);

```

If the rocket is destroyed or is left stationary then you can ignore its mass here.

This will mean that your ship should gain all the momentum of the rocket and have its speed increased by a lot.

---

If this is not the case please let me know and I'll take another look.

---
Tags: physics, javascript, collision-resolution, trigonometry
---


# Question
Title: My script isn't deleting or destroying my prefab game object in Unity2D
My script isn't deleting this game object once it reaches a certain position in my game. This is my script:

```
public float left;

public GameObject enemyLeft;

void Start ()
{
    enemyLeft= GameObject.Find("Enemy Left");
}

void Update()
{
    if (transform.position.x < left)
    {
        Destroy (enemyLeft);
    }
}

```

`enemyLeft` is a prefab `gameObject` that is being spawned in by my spawner.

This is the script where I intend to `Destroy` the game object:

```
    public float left;

    public GameObject[] enemiesLeft;

    void Update()
    {
        for (int i = 0; i < enemiesLeft.Length; i++) {

            if (enemiesLeft[i].transform.position.x < left) {
                Destroy (enemiesLeft[i]);
            }
        }
    }

```

Why isn't it deleting the game object?

# Answer
Calculate position of `enemyLeft` instead of script holding object.

```
   void Update()
    {
        if (enemyLeft.transform.position.x < left)
        {
            Destroy (enemyLeft);
        }
    }

```
> 1 votes

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


# Question
Title: How to play an animation backwards in Unity?
I know this question has been asked before but it all involves using the Animation(?) component, so that is no longer any good in Unity 5.3.1f1, I explain a bit more later.

I'm trying to simply get an animation to play backwards. On the object that I want to have an animation play backwards on, I have an animator.

```
private Animator anim;
...
anim = GetComponent<Animator>();

```

If I do:

```
animator.speed = -1.0f;

```

It tells me *Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode != AnimatorRecorderMode.Offline*

So I try putting on an Animation component on the game object, and making the clip the animation.

Every time I do anything with the Animation component in script, it tells me the component must be marked as Legacy. That is no good, because when I tried making it Legacy it caused multiple problems including not being recognized by the Animator. Also GetRef errors. The entire Animation component seems like it's treated as legacy now or is just broken.

So I decided well maybe I could just try to get the animation to play backwards in the animator and having the animator record it, and then using that backwards recorded animation in the actual game. I cannot figure out how to this, even if I click record in the Animation view anim.recorderMode != AnimatorRecorderMode.Record. I don't know what to do. All I want to do is play the same animation backwards without having to copy and paste an animation in the Project and moving all of the keys around so that they are reversed. Please help. Unity's animation system seems so convoluted in script.

# Answer
> 1 votes
This can all be done in the Controller.

All you need to do is create another state. In my example I created a walk and walk backwards:

The walk state is just the walking animation, it takes in a float parameter called "Speed" and transitions from idol when speed is greater than zero.

The walk backwards state, which is simply the walk animation played with speed -1 (see below) can be transitioned to from the walking state if the speed is less than zero. ( an unconventional state machine because you can't go from idol to backwards or from backwards to forwards, but this was contrived for the example.)

# Answer
> 4 votes
I've been working with Unity 5.3 and another way I found is to create a new float parameter for the animator controller. Call it `direction`. Enable it as a multiplier parameter for the Speed (with Speed equaling `1`) in the state you wish to play in reverse.

Then in the scripting set 'direction' = -1f and the animation plays in reverse.

```
Animtor anim = GetComponent<Animator>();
anim.SetFloat('direction', -1);

```

---
Tags: unity, animation, game-recording
---


title: Unity UI Animation Transition

text:
# Question
Title: Unity UI Animation Transition
So I'm fine with gameplay coding, but menus are something I'm still very new to.

I was watching Unity's own video on how to deal with Buttons and I thought I'd try mock up my own button animation much like they had. It works wonderfully, there's just one minor issue.

So a Button can go from 'any state', so either pressed, highlighted or normal (or disabled but I'm not using that). When I hover it works but it'll go straight back to normal once it's 'time'/'cycle' has completed. I figured that to fix this, I ought to add a transition between Highlighted and Normal.

This does work, providing I say that 'Normal' must be true before transitioning between the 2. Here's my issue however - when I click, the button hits pressed fine, then goes back to highlighted, and won't go back to normal unless I just click the background/anything that isn't the Button.

How can I get it to go straight to normal once the mouse is no longer on the button? I thought maybe a trigger collider with OnExitTrigger type function but that seems messy, isn't there a way to do this IN animator?

# Answer
This can be done with an `Pointer Exit` Event Trigger. But there is a little more work if you want to do it without coding the whole thing.

Use Boolean for Pressed and Highlighted instead of Trigger parameter on transition conditions. And add an Event Trigger of `Pointer Exit` having `Button` component in it with `OnDeselect` method selected.

Transitions: State\_A \>\> State\_B (Bool)

Normal \>\> Highlighted (Highlighted true)

Highlighted \>\> Pressed (Pressed true)

Pressed \>\> Highlighted (Pressed false)

Highlighted \>\> normal (Highlighted false)

But still suggest to do it programmatically for more control. You will be using a manually created animator controller for it instead of auto generated one.
> 0 votes

---
Tags: unity, animation, ui-design
---


# Question
Title: How to Detect Collision Between Entity and Viewport
I am using Crafty.js. I want the player to die when they hit the side of the viewport (they need to keep moving to stay alive). How do I detect a collision between the player entity and the side/edge of the viewport? I have looked at Crafty.viewport, but have not been able to find anything useful.

# Answer
> 0 votes
Use your entity's 2D method within combined with your viewport's property bounds as input argument. It will check if your player's rectangle is within the viewport.

---
Tags: collision-detection, javascript, crafty
---


# Question
Title: Why do most FPS games have a machine gun, shotgun, and sniper rifle?
Most folks who've played FPS games would have noticed that the same weapons tend to reappear again and again, such as machine guns and shotguns. There was once a lot of innovation in the types of weapons in the genre's early days (see *Duke Nukem 3D* or *Unreal Tournament* for example), but in recent years the weapons tend to be cosmetic variations on a few standard types (warning: tvtropes link).

Why has this happened? I believe a large reason is that these standard guns serve distinct gameplay roles or purposes, so that even if they are replaced with a gun that is named differently or looks different, they act almost the same. If so, what are these roles, and could they be replaced with a gun that acted differently? For example, is it possible to replace the shotgun with something that was not semi-automatic, or fired a burst of pellets, without affecting the role?

# Answer
> 15 votes
Part of the reason has to do with the simple fact that games favoring real, or plausibly realistic, guns are currently popular right now (perhaps owing to the success of similar games). That reason is a bit anthropological in nature, so I won't comment on it further.

Another large part is, as you said, these guns basically fulfil key mechanical roles:

* An assault rifle or machine gun acts as a short-to-mid range general-purpose weapon. A very high rate of fire is generally balanced by weak single-impact damage poor long-range performance, and high kick or recoil.
* A sniper rifle serves as a long-range, high-damage pinpoint weapon. A slow rate of fire generally compensates for its power, and its scoping ability discourages close-range use due to the significant decrease in immediate situational awareness.
* A shotgun is a "trench" weapon, a short-range "panic button" that does lots of damage, but only in close quarters, and only for a short time before an extensive reload period.

Examining those mechanical properties, then, one could certainly see how it might be possible to replace the guns in those roles.

* In a game that does not need to adhere to plausible reality, one could simply invent totally new weapons or devices that provided the same mechanics. This was done, for example, with the weaponry in "Hexen" and games of its ilk, which used magic or magical artifacts since guns did not fit the setting. This is less viable in games that *have* guns; players will tend to categorize them in the ways above regardless of what you actually call them in-game, since real-world analogies (and habit) are more natural.
* In a game that does have realistic guns, then, one might be able to reasonably swap one or two properties around between the various archetypes to mix things up without causing too much trouble with suspension of disbelief.

# Answer
> 5 votes
> Why has this happened?

**This HASN'T happened.**

Duke Nukem 3D and Unreal Tournament (to use your examples) were creative games, both were trying lots of exciting new things, in new themes, in new ways.

**But most other games from those eras weren't doing that.**

Quake 1, for example, had a pistol and a shotgun and a machine gun and a rocket launcher and etc. So did Doom. So did Quake 2. So did Sin. So did Half Life. So did Wolf3D. So did Marathon. So did System Shock. So did Dark Forces.

Yes, a few old FPS games were inventive in their creation of bizarre new types of weaponry, but they were far and away the exception: the vast majority of older FPS games were pedestrian in their weaponry, using standard weapon tropes which roughly evoked real-world weaponry.

In the same way, the vast majority of modern FPS games are using these familiar weapon tropes, but there are a few creative and inventive modern games experimenting with new ideas (for example, Painkiller or Bulletstorm), exactly the same way that Unreal Tournament and Duke Nukem 3D experimented way back then.

There are good reasons to use common weapon tropes, instead of inventing new weapon types. They're familiar to players. They're easy to design. Players don't have to be taught how or when to use them; players already know them from all the other games they've played, or from a general familiarity with pop culture. I think I'd be shocked if they **weren't** the most common weapon designs across all eras of video gaming.

Which isn't to say that new weapon types aren't fun. They're just a little more challenging and time-consuming to get right, and require more explanation to teach players how and when to best use them. And if that's not what your game is fundamentally about, then I can understand why somebody might want to focus their design efforts somewhere a little more interesting than on which bullet blows up when and how big the resulting explosion is to be.

# Answer
> 4 votes
Aside from Josh's answer you have to keep in mind something else: players know what each of these weapons does. If I pick up a sniper rifle I know what I can probably do with it (shoot long distances, scope) and when I pick up a shotgun I also know to use it on shorter distances. If these weapons are replaced by say a deathRay and a doomshooter I might not know what each of these weapons know making life harder on newbies.

# Answer
> 1 votes
Forget the names, think of them as roles.

You have weapons optimized for short, medium and long range. For the sake of gameplay you don't want to allow any of them to be superior over more than it's intended range or you'll end up simply killing off the other options.

Pistols aren't used because you never carry a pistol into battle unless you don't have a choice. They are categorically inferior to all the standard weapon types and only exist for use by those whose actual odds of using them are remote. (Law enforcement, self defense, aircraft crew etc.)

You can have a game where they can fire other things (I'm thinking of XCOM and it's ilk) but that does not change their fundamental nature.

What other direct-fire weapon could exist without replacing one of these three?

Note that this does not mean there can't be things other than direct fire weapons. While I'm not a FPS player I've seen many people playing them and grenades are common. I've also seen rocket launchers. Rocket launchers always have to be ammunition-limited to keep them from eliminating the machine gun and sniper rifle roles.

Again, you can put different things in your grenades, they're normally still grenades. (Although one variation exists in this--I'm thinking of XCOM games with some friendly-safe grenades.)

# Answer
> 0 votes
Perhaps you might like a slingshot? Or maybe a bow and arrow? Exactly how many weapons are there anyway? How about a potato gun? Choice of weapons need to be selected for play ability, realism, and any other factors included in the game.

---
Tags: game-design, first-person-shooter
---


# Question
Title: Why do most racing games have tracks that are closed loops?
In most racing games (Mario Kart, Sega Rally, F-Zero, etc.), racers typically make some number of laps in a closed circuit. The most notable exceptions that come to mind are all arcade games, or arguably not even a racing game (Trackmania, OutRun, the Cruis'n series). **Why would a designer want to build tracks as closed loops, and why is it so commonplace?**

# Answer
I'm not sure about your assertion of "most" - many games like GT, DriveClub, etc, have many point-to-point races...

But there are two reasons to this:

Firstly, many real-life races are lap-based on closed circuits (Formula 1, Nascar, etc), so gameplayers might expect this as a standard.

Secondly, and from a game design point of view, putting multiple laps on a closed circuit means you can multiply the game time for less game design (a 4 lap race on a 1 mile circuit means only 1 mile of track and environment design - a 4 mile point-to-point means 4 miles of track and environment design).
> 36 votes

# Answer
From a design point of view, it's advantageous for new players to learn the placement of powerups, dangers and other landmarks on the track in the first lap so they can focus more on gameplay for the remainder of the game.

The sooner the player can get through the learning phase of the game, the sooner they can start mastering the other aspects of the game.

As Bushnell's Law states: "All the best games are easy to learn and difficult to master."
> 26 votes

# Answer
In racing games, going as fast as possible is only part of the game. It would not be as interesting to race against a timer. Loops force interaction between players, as even those that are far ahead are near the others. Loops allow multiple chances to cut each other off, or to use power-ups against opponents. As an example, the banana peel item would have much more limited use on a point to point race.
> 3 votes

# Answer
A couple answers already covered the design aspect of it pretty well (more stuff = more work).

Something that hasn't really been brought up yet is how laps measure skill. Someone did mention that it is an "endurance" sport for professional racing. This is a pretty big factor in real life; no so much video games.

The other skilled aspect of the lap system is what is important. Determining relative skill is extremely complicated. There are so many active variables that the skills between two close opponents are often not the only factor in determining victory. A big factor is variance. Not everyone is going to have their best race every time. A lap system gives a better measure of consistency by testing performance on the same track multiple times in one race.

It's like doing an measurement 3 times instead of 1 to make sure you have accurate values.
> 2 votes

---
Tags: game-design, game-mechanics, level-design, racing
---


title: How to unit test XNA Game object

text:
# Question
Title: How to unit test XNA Game object
I'm doing a hobby game project using Visual Studio 2015 and XNA, via the MonoGame implementation. I wanted to do some unit testing, as I recently discovered this feature in Visual Studio, and want to get a feel for how it can be used.

The problem is, I can't get it to work with the XNA Game object, or anything derived from it.

This is a simple instantiation test I made:

```
[TestMethod()]
public void MyTest()
{
    try
    {
        MyObject Test = new MyObject();
    }
    catch
    {
        // Fail the test if any exception occurs in the constructor.
        Assert.Fail();
    }
}

```

Whenever I use my own object in place of `MyObject`, the test passes. When I use `MyGame` (derived from `Game` and with my own properties/methods), the test fails. I've tested the same object in the debugger, and it doesn't throw an exception.

Any idea what I'm doing wrong, or is the `Game` class just incompatible with Visual Studio unit testing?

# Answer
`Game` class controls lots of things, like a game window and graphics resources. The class has huge (and somewhat time-consuming) global side effects, which make it a bad candidate for unit testing. Unit testing works best when classes under test are isolated and have no global state. I'd practice testing with simpler classes.

In general, I would avoid any references to the `Game` class in unit tests as much as possible because of the global effects. In some cases, it is unavoidable... but be prepared for hacks and maintenance cost. It is not impossible - some MonoGame unit tests use their own `Game` class. Relatedly, there have been some (hard-to-debug) issues with game lifecycle and performance.

Without the exception details it's difficult to say for sure, but something (my guess: creating the game window) conflicts with the test runner.
> 1 votes

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


# Question
Title: How to improve this shader's performance?
I have a scene with 150000 instances. I use glsl and opengl 4.0. Shader A is 2 times slower than shader B. I.e. with shader A I get 20fps, with shader B I get 40fps on average. What can I do to improve shader A?

Shader A:

```
#version 400

struct Light {
   vec3 position;
   vec3 intensities; //a.k.a the color of the light
   float ambientCoefficient;
   float attenuation;
};

uniform bool useLight;
uniform mat4 modelMatrix;
uniform bool useTex;
uniform sampler2D tex;
uniform Light light;
uniform vec4 diffuseColor;

in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragVert;

out vec4 finalColor;

void main() {
    vec3 normal = normalize(transpose(inverse(mat3(modelMatrix))) * fragNormal);
    vec3 surfacePos = vec3(modelMatrix * vec4(fragVert, 1));

    vec4 surfaceColor = vec4(0,0,0,1);

    if(useTex) {
        surfaceColor = texture(tex, fragTexCoord);
    }
    else {
        //surfaceColor = diffuseColor;
        surfaceColor = vec4(0,1,0,1);
    }

    if(useLight) {
        vec3 surfaceToLight = normalize(light.position - surfacePos);

        //ambient
        vec3 ambient = light.ambientCoefficient * surfaceColor.rgb * light.intensities;

        //diffuse
        float diffuseCoefficient = max(0.0, dot(normal, surfaceToLight));
        vec3 diffuse = diffuseCoefficient * surfaceColor.rgb * light.intensities;

        //attenuation
        float distanceToLight = length(light.position - surfacePos);
        float attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));

        //linear color (color before gamma correction)
        vec3 linearColor = ambient + attenuation*(diffuse);

        //final color (after gamma correction)
        vec3 gamma = vec3(1.0/2.2);
        finalColor = vec4(pow(linearColor, gamma), surfaceColor.a);
    }
    else {
        finalColor = surfaceColor;
    }
}

```

Shader B:

```
#version 400

struct Light {
   vec3 position;
   vec3 intensities; //a.k.a the color of the light
   float ambientCoefficient;
   float attenuation;
};

uniform bool useLight;
uniform mat4 modelMatrix;
uniform bool useTex;
uniform sampler2D tex;
uniform Light light;
uniform vec4 diffuseColor;

in vec2 fragTexCoord;
in vec3 fragNormal;
in vec3 fragVert;

out vec4 finalColor;

void main() {
    finalColor = vec4(0,0,0.7,1);
}

```

# Answer
At first you should pre-compute as much data as you can and avoid computing the same values for every pixel.

You have such a fragment:

```
transpose(inverse(mat3(modelMatrix))

```

This inverts the matrix, which is not so trivial operation and despite the fact that input data are the same for each pixel (so the results will be the same) it's recomputing this for every pixel. Compute it once, before rendering and pass the result as another matrix, like you do with the `modelMatrix`.

Later, you're also normalizing the `(light.position - surfacePos)` vector but you're also computing the `length` of it, so it results in two `sqrt` operations instead of one.

Additionally, depending on your hardware you may find that using `if's` in a pixel shader may lower your performance. If that's the case you could prepare few distinct versions of your shader and batch your instances depending on the `useLight` and `useTex` properties.

EDIT:

You may also try to lower the OpenGL version defined in shaders, to be the lowest one supporting your features. In theory it shouldn't do much but depending on drivers and HW vendor the practice may differ... (i.e. if your GPU supports OGL 4.0 it often means that it's fast in OGL 3.0 but very slow in 4.0, but you need to test it on specific case).
> 15 votes

# Answer
Looking at this line in particular:

`vec3 normal = normalize(transpose(inverse(mat3(modelMatrix))) * fragNormal);`

working out the inverse of a matrix is very taxing, and should be precalculated by the cpu instead of forcing the gpu to waste time messing around with it.
> 3 votes

# Answer
There's not a whole lot you can do; the simple reality is that shader A does more work than shader B, so it's always going to run slower.

We can close the gap somewhat however. I can't give you definite figures for how much, it all depends on performance characteristics of the rest of your program, so treat these are general good practice.

```
transpose(inverse(mat3(modelMatrix)))

```

That's a lot of inversions and transpositions per frame. Do it on the CPU instead, one time only (or at least only when modelMatrix changes) and send the inverse/transpose matrix as an additional uniform. If ALU operations are a bottleneck for you, this should gice you the biggest increase.

```
if(useTex) {

```

Branching is not the death that it used to be, but you can still avoid it here (and save a uniform slot) by creating a 1x1 texture (of the appropriate colour) and binding that instead.

```
if(useLight) {

```

More branching. In this case there's no obvious alternative (such as the 1x1 texture) so I'd encourage you to split this condition off into a third shader and benchmark both (i.e. 2 shaders with a branch versus 3 shaders without). Depending how often you need to change shaders you may or may not see a performance difference when compared to branching.
> 3 votes

---
Tags: glsl
---


# Question
Title: Make Unity game using files directly from game directory
For stats of enemies, and several other kinds of info, I've decided to use not inspector fields or hardcoded values, but to store values to some XML and other types of files, and read them from scripts, obtaining required values. And I want this files to stay in game folder, not packed to \*.assets file, because I'd like to have possibility to quickly modify this values without need to rebuild whole game.

So, how can I mark asset in editor, that it should not be included to \*.assets, but stay in unchanged form in game folder?

**UPDATE:** I will slightly rephrase what I want to achieve. I need possibility to have file in game directory, so I can read it from game, and *I'd like to have this possibility in both editor and built game.* So, as for answer, I will also receive information about what folder is considered as game folder in editor.

# Answer
> 1 votes
You will need to save your things in Streaming Assets folder:

http://docs.unity3d.com/Manual/StreamingAssets.html

And using some serializer, if you are using Unity below version 4, you should use whydoidoit serializer:

https://www.assetstore.unity3d.com/en/#!/content/3675

If you are using higher versions you can try an adapted version of this from TheSniperFan called unityserializer-ng:

https://gitgud.io/TheSniperFan/unityserializer-ng/tree/master-pre-5.4

Or even my API that is a forked and simplified version of it with a few things more, but it's still very undocumented and messy:

https://github.com/Ikillnukes/Lerp2API (it doesn't have scene saver, but I will implement it)

The way you can achieve this is by doing this, imagine you have an gameobject called "myobject", you can do myobject.SaveTreeObject(); to convert it to a byte\[\] variable (you can save it using System.IO.File.WriteAllBytes) and to load it by using LevelLoader.LoadObhectTree(Action) being careful, because the action represents the function that load the object.

My API currently does that I said.

Good luck.

# Answer
> 1 votes
Put this in a editor folder inside the Assets folder.

```
using System.Diagnostics;
using UnityEditor;

public class CustomBuild {

    [MenuItem("MyTools/Windows Build With Postprocess")]
    public static void BuildGame()
    {
        // Get filename.
        string path = EditorUtility.SaveFolderPanel("Choose Location of Built Game", "", "");
        string[] levels = new string[] { "Assets/Scene1.unity"};

        // Build player.
        BuildPipeline.BuildPlayer(levels, path + "/BuiltGame.exe", BuildTarget.StandaloneWindows, BuildOptions.None);

        // Copy a file from the project folder to the build folder, alongside the built game.
        //This does not check if the file already exist or not you need to do this by yourself.
        FileUtil.CopyFileOrDirectory("Assets/test.txt", path + "/test.txt");

        // Run the game (Process class from System.Diagnostics).
        Process proc = new Process();
        proc.StartInfo.FileName = path + "/BuiltGame.exe";
        proc.Start();
    }
}

```

I'm not sure how you can do this on mobile. On Android for example you might want to create the file when your game first launches to some extern directory on the device and modify it from there. Also not sure how it will work on Mac since I know almost nothing about Macs. Have fun ;)

---
Tags: unity, assets, asset-management
---


# Question
Title: Showing background transparent image in android
I have a image with transparent background created from photoshop.

I added this to my android game which I am creating using libgdx. But when I add it to that, it is shown with white background like following.

Whats the reason for this? How can I fix this?

# Answer
> 0 votes
You'll want to stick a

```
batch.enableBlending()

```

for the sprite inside of the `batch.begin()` and `batch.end()`. The reason this works is because what blending does is merge the translucent pixels with the previously drawn ones.

Because blending can incur a performance cost from all the merging magic as opposed to whopping on a straight texture, it's beneficial to simply disable blending unless you're using it yourself.

e.g

```
batch.begin();
batch.disableBlending();
// draw all the other stuff FIRST to save on performance
batch.enableBlending();
myCoolSprite.draw(Batch);
batch.end();

```

For more information about this area you can check out This handy old wiki page.

---
Tags: android, libgdx, textures, image, transparency
---


# Question
Title: Transferring my OpenGL PC game to PS4 and/or XBox One
I want to transfer my OpenGL PC game to consoles, PS4 and/or XBox One.

It's a complex application, where many calculations (incl. fast fourier transformations) via FBOs and Transformfeedback are performed within OpenGL. What is the best way to bring it to the PS4?

Or is it easier to implement the game in an engine like Unity or Unreal. As far as I know they have console support? An advantage would be that we could offer our methods as plugin/asset. We are planning to do this too.

There are a lot of glsl-shaders and OpenGL-Api-Calls. Is it possible at all to "translate" that into an engine like unreal? Or would we have to use the engines "predefined" rendnering mechanisms? We basically need shaders operating on floating point textures, changing render targets frequently and transform feedback if possible. We also need low level acces to shading attributes like changing pointsize in the vertex shader etc.

And I really would like to know which is less work. I could image that it is possible to absctract all the Api-Calls in classes/functions and then where first all the OpenGL-calls are implemted and then we would do an implemetation for the console api. Is this realistic on the PS4 Api?

I know that Direct X will have a different design and therefore abstraction itself won't be enough. I believe porting to an engine might be even more work as you have to respect its structures.

# Answer
> 6 votes
Unfortunately, I asked a similar question last year, and the answer was clear: neither PS4 nor Xbox One have OpenGL support. If you want to make your game works on them without using another engine, you will have to rewrite the entire rendering API (anything directly related to OpenGL or shaders) into an API supported by a console.

Unity and Unreal engines do have PS4 and Xbox One supports. But as rendering API calls are often the deepest and least accessible part in game engines, it will be hard to "translate" it from your own code to one of them, especially if your rendering mechanism is different from theirs (which is most probable).
And of course, it would mean totally rewrite your game if you didn't use the same language than the one used by those engines (C++ for Unreal and C#/JavaScript for Unity).

So any solution would require a lot of work. But if you are making complex calculations using every mechanism of the rendering API, the first one shall give you more possibilities.

---
Tags: opengl, xbox, playstation4
---


# Question
Title: How to generate a 2D tile planet with perlin noise?
I recently tried reading about procedurally generating and I found out that perlin noise is probably a good way to do it.

Now one way of generating 2D terrain would be to have 2D perlin noise and depending on the height of the noise at a certain point place a certain tile. My question is now, how could I modify the perlin noise so that it generates a planet? It would probably need to be a circle, in the middle of which the noise is high, while outside of the circle its pretty low. The overall shape of the noise would be rectangular.

In the end it should look something like this, but noisy: https://i.stack.imgur.com/QqFWH.png

Any advice or articles that help?

# Answer
> 3 votes
Got it now, I wanted to create the planet with perlin noise, but changed to simplex noise, which is similar.

To get the planet shape, I used a radial gradient, but the one used for creating island was too smooth, which wouldnt result in a planet shape, so I created a radial gradient, which ends more abruptly, like this (the black background beyond the circle is actually transparent, I dont know how to make it white).

After that just generate the simplex noise, get the alpha data from the gradient (in my case) and then go through every pixel and subract 1 - (the gradient alpha value from the pixel) from the perlin noise value.

At this point, you already have a noise in the shape of a planet, to get terrain, you can get the noise values from 0 - 1 and compare them: If the value is 0, do nothing, if its less than 0.4, draw dirt, if its less than 1, place stone ( and then some special things to place grass).

After all that, you get

Heres the improvised code:

```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class PlanetGen {
    public static void main(String[] args) throws IOException {

        // GET GRADIENT DATA
        File gradientFile = new File("assets/gradient.png");

        BufferedImage bi=ImageIO.read(gradientFile);
        int[] pixel;

        double highestAlpha = 255;

        double[][] alpha = new double[bi.getWidth()][bi.getHeight()];

        for (int y = 0; y < bi.getHeight(); y++) {
            for (int x = 0; x < bi.getWidth(); x++) {
                pixel = bi.getRaster().getPixel(x, y, new int[4]);

                alpha[x][y] = 1 - (pixel[3] / highestAlpha);
            }
        }

        SimplexNoise simplexNoise=new SimplexNoise(100,0.1,5000);

        // GENERATE SIMPLEX NOISE
        double xStart=0;
        double XEnd=500;
        double yStart=0;
        double yEnd=500;

        int xResolution=bi.getWidth();
        int yResolution=bi.getHeight();

        double[][] result=new double[xResolution][yResolution];

        double lowestNumber = 0;
        double highestNumber = 0;
        for(int i=0;i<xResolution;i++){
            for(int j=0;j<yResolution;j++){

                int x=(int)(xStart+i*((XEnd-xStart)/xResolution));
                int y=(int)(yStart+j*((yEnd-yStart)/yResolution));
                double currentNumber = result[i][j] = 0.5*(1+simplexNoise.getNoise(x,y));

                if(currentNumber < lowestNumber) lowestNumber = currentNumber;
                if(currentNumber > highestNumber) highestNumber = currentNumber;
            }
        }

        // NORMALIZE NOISE DATA
        for(int i=0;i<xResolution;i++){
            for(int j=0;j<yResolution;j++){
                result[i][j] = (result[i][j] - lowestNumber)/(highestNumber - lowestNumber);
            }
        }

        //SUBRACT GRADIENT FROM NOISE
        for(int i=0;i<xResolution;i++){
            for(int j=0;j<yResolution;j++){
                result[i][j] = Math.max(0, result[i][j] - alpha[i][j]);
            }
        }

        // DRAW PLANET IMAGE
        int tileWidth = 8;

        BufferedImage imgDirt = ImageIO.read(new File("assets/dirt.png"));
        BufferedImage imgGrass = ImageIO.read(new File("assets/grass.png"));
        BufferedImage imgStone = ImageIO.read(new File("assets/stone.png"));

        BufferedImage img = new BufferedImage(bi.getWidth()*8, bi.getHeight()*8, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = img.createGraphics();

        for(int x = 0; x < xResolution; x++) {
            for(int y = 0; y < yResolution; y++) {
                double value = result[x][y];

                if(value == 0) {
                    g2.setColor(Color.BLACK);
                    g2.fillRect(x*tileWidth, y*tileWidth, tileWidth, tileWidth);
                } else if(value < 0.4) {
                    boolean isGrass = false;
                    for(int i = 0; i < 3; i++) {
                        for(int j = 0; j < 3; j++) {
                            if(result[x-1+i][y-1+j] == 0) isGrass = true;
                        }
                    }
                    if(isGrass) {
                        g2.drawImage(imgGrass, x*8, y*tileWidth, tileWidth, tileWidth, null);
                    } else {
                        g2.drawImage(imgDirt, x*8, y*tileWidth, tileWidth, tileWidth, null);
                    }
                } else {
                    g2.drawImage(imgStone, x*8, y*tileWidth, tileWidth, tileWidth, null);
                }
            }
        }

        ImageIO.write(img, "png", new File("./planetwithtexture.png"));

        g2.dispose();
    }
}

```

---
Tags: procedural-generation
---


title: Develop bots for CS:GO

text:
# Question
Title: Develop bots for CS:GO
I'm working on a project where we would like to create a more "intelligent" bot in CS:GO (as a training-bot that you can play against in offline mode). We're currently in the start-up process and there's some initial questions. Would be greatly helpful if anyone can help out with some answers!

After some research there seems to be difficulties developing bots for CS:GO as a third-party-bot developer. Is it only VALVE that develops bots for CS:GO or is it possible for a developer to create a bot in CS:GO? Is anyone here comfortable with developing bots for games such as CS:GO? If so, it would be awesome to get some more in-depth answers about our project.

# Answer
While you're able to change their general difficulty, skill, what they look like, what they sound like and what they buy, you're unable to really change how they work and where they go and what they do. This means that you'd also likely need to hook into the game's code or write your own server software that would be able to modify the bots itself. Note that both of these are *likely* against Valve's TOS.

Files that include variables/code for bot behaviour:

* `/csgo/botprofile.db` \- skill variables, voice pitch, buying behaviour
* `/csgo/botprofilecoop.db` \- same as above, but for coop
* `/csgo/botchatter.db` \- how and when bots talk through the radio

Note that a community member has made Bot AI Framework for DotA 2. While they no longer share the same engine, you might find it useful for your research.
> 1 votes

---
Tags: steam
---


title: Is Time.deltaTime framerate dependent?

text:
# Question
Title: Is Time.deltaTime framerate dependent?
I have a game that calculates your score via `Time.deltaTime` (the more time the more score). On my PC I get about 1200 points if I just idle the game while on my phone I only get about 400 points.

I believe my code must be FPS dependant and that's why my phone is getting a lower score for the same time.

Here's the code:

```
void Update ()
{
    time += Time.deltaTime;

    score += (int)time;

    timerLabel.text = score.ToString();
}

```

Sorry if it's something very obvious. I'm quite new at c#.

Can't seem to get the solution to work. It just stays at 0:

Full Code:

```
    using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class EndGame : MonoBehaviour {

    public Text textWin;
    public Text timerLabel;
    public GameObject retryButton;
    public GameObject points;

    private Vector3 offset;
    private float time;
    private float score;

    void OnTriggerEnter (Collider col) {
        if (col.gameObject.name == "Player") {
            setWinText ();
            retryButton.SetActive (true);
            points.SetActive (false);
        }
    }

    void setWinText () {
        textWin.text = "Final score: " + score.ToString();
    }

    void Update ()
    {
        time += Time.deltaTime;
        if (time >= 1.0f) {
            ++score;
            score -= 1.0f;
        }

        timerLabel.text = score.ToString();
    }

}

```

# Answer
`deltaTime` is the (or at least, *a*) correct thing to be basing a time-based score on. It's value does vary with the framerate, of course, since it tracks real-time elapsed time between one frame and the next. On faster frames, it will be a smaller value than on slower frames, but it will always measure real time, so it's basically the thing you want to be using.

*How* you are using it is wrong, though.

`deltaTime` is a floating point value, when you cast it to an integer you truncate (drop) the decimal portion of the value. This means that on very fast frames, when `deltaTime` is less than one, you add zero to the score. On every other frame you add some value to the score, but you're compounding the error more-or-less randomly.

One way to do this which doesn't exhibit this issue is to accumulate delta time until it measures one second, and *then* add one to the score, resetting the accumulator and *preserving* the factional part of the number. Something *like* this, conceptually:

```
void Update() {
   scoreTimer += Time.deltaTime;
   if (scoreTimer >= 1.0f) {
     int integer = (int)scoreTimer;
     score += integer;
     scoreTimer -= integer;
   }

   // ...
}

```

This will also make the score counter visually increase at the same fixed rate, instead of as fast as your framerate is.

The cast to `int` is to extract the whole-number part of the accumulator and add that to the score, and then to subtract that whole-number part out of the accumulator so you preserve the accumulation of fractional time. This helps correct for frames that are *extremely* slow, in excess of one second long. You could also use `Math.Round`.
> 3 votes

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


# Question
Title: How to calculate area to fill in this Snake/Qix game variant?
I have a game which is a Snake/Qix variant.

The player controls a line which is moving on an island. Player has possibility to leave the island in order to connect that island to itself. Once the connection is made, the new area formed by the connection becomes part of the island (see picture: red line is the path the snake has made while outside the island, dark red pixels are the area/island).

I am trying to find a algorithm (even bruteforce) how to fill the new area (in other words how to do transition between first and second line on the picture).

What I have in mind is to run a path finding algorithm between the enter/exit points. If there is a path, it means the snake connect the island to itself. The path (in green) and red line together forms a closed polygon which can then be filled (how ?)

As it is now, the data is simply defined a 2D array of pixels (eg : 0 = empty, 1 = island, 2 = player snake)

# Answer
> 2 votes
One way you could do this, is by performing multiple flood fills in a defined area. You could keep track of your Path's Max and Min X and Y positions, so that you can have a defined area to check. This would look something like this:

Then, process the black tiles inside of this area with a flood fill. If the floodfill at any point hits that Yellow border, then you know it is not going to be inside of your path. You can discard these tiles, and move on to the next Black tile.

If the flood fill never reaches that yellow border, than you know you are inside of the path, and you can fill it all in.

# Answer
> 3 votes
I think you should flood from the outside, start with the bounding box of your snake path and the island and then use the unmarked edge pixels as a seed to flood your "true" outside. Then you can mark the inverse as your island.

The issue with flooding from the inside, is that you will have to keep track of which flooded pixel belong to which seed, since you have to be able to remove them when you hit the boundary.

---
Tags: algorithm, path-finding, pixel
---


# Question
Title: Using XAudio2 to Process Microphone Input
I am trying to come up with a solution to process microphone input for a game. Not entirely sure where to start. I was looking into using XAudio2, but it doesn't seem to have support for microphone processing? Is this correct? What do most companies in the industry currently use?

# Answer
> 0 votes
XAudio2 is intended for real-time mixing, source-rate conversion, and DSP effects such as position audio as is commonly used in games. It does not handle audio input which on Windows is typically done with Windows Core Audio (aka WASAPI)--on Windows XP input was part of DirectSound.

You can capture data using WASAPI and then process it using XAudio2 for output.

See the WindowsAudioSession, CaptureSharedEventDriven, and CaptureSharedTimerDriven samples

# Answer
> 0 votes
I used OpenAL a while ago, it may fit your needs.

The pro's are the portability and easy setup, you have also access to a good documentation and guide.

Take a look at their website, you can find there everything you will need: OpenAL website

---
Tags: voice, xaudio2
---


# Question
Title: Why do my buttons look like this? (unity game development)
They are extremely ugly? I can't figure out why.

# Answer
I'm not completely sure but I do have two ideas for you to try:

1. Increase the texture resolution to make it more sharp.
2. It doesn't look to be using distance fields, just regular bi-linear filtering. Read about Distance fields, which is one of the best ways to render sharp text, maybe this will help.
> 2 votes

# Answer
It's scene view in 3D. Look at "game" window in Unity or open, if you closed it. You can also click "2D" in scene window. Here:
> 0 votes

# Answer
You should edit your **Import Settings** fields to fit the image to your desires (this is done by clicking on the texture in the **Project Browser** window):

https://docs.unity3d.com/Manual/ImportSettings.html

By changing **Wrap Mode** to **Clamp**, **Filter Mode** to **Point**, and setting the highest possible resolution in the **Max Size** list, and setting the **Format** to **Truecolor**.

Something like this should be enough:

Just click **Apply** and that's all!

Good luck!
> 0 votes

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


title: Conversion of a C++ library to DLL

text:
# Question
Title: Conversion of a C++ library to DLL
I'm developing an augmented reality application and I'm supposed to use the ALVAR library for AR marker detection. I use Unity as the game engine and unfortunately it doesn't support C++. Is there any possible way to use the C++ library as a DLL?

# Answer
> 1 votes
You should be a little bit more versatile, you should search resources from other people, maybe by using this it's a good start:

https://github.com/bara3r/AR-Unity

It says Unity 3.5.5 Pro, don't worry about this, because Unity 5 has all Plugins features from Pro lower versions.

And the Unity Import Script API should translate it to the newest code! Maybe you will see some compiler warnings.

---
Tags: unity, c++, augmented-reality, dll
---


# Question
Title: Simplst possible TBN-Matrix giving weird results
I'm implementing normal mapping and was trying different techniques of doing that. All seemed not to give me a correct result (e.g. the normals point in weird directions). To find the problem, I broke everything down to the simplest possible solution, but I cant find the problem.

Here is a picture of my scene outputting only the world-space normals:

And here is the scene outputting the transformed normals with the normal map:

As you can see, the normals are not pointed the way they should be (green should be to the right, for example). Here is the way I caluclate the TBN-Matrix (I know, its not the correct way of doing that, but I tried the "correct" ways too).

```
vec3 tangent = cross(worldspaceNormal, vec3(0,0,1));
vec3 biTangent = cross(tangent, worldspaceNormal);
mat3 tbn = mat3(tangent, biTangent, worldspaceNormal);

vec3 map = texture(normal, texCoord).rgb;
map = 2 * map - vec3(1);

outNormal = vec4(tbn * map, 0.0);

```

The `worldspaceNormal` is just the normal of the surface multiplied by the model-matrix, with w-component `0.0`, of course.

# Answer
> 1 votes
Found the problem. The TBN apparently needs to be constructed as the following: `mat3(worldspaceNormal, biTangent, tangent);`. So tangent and normal need to be flipped. Don't know why, maybe a Vulkan thing.

# Answer
> 0 votes
The normal matrix should be the transpose inverse of the modelview matrix. You can't simply multiply with model-matrix. Hope this clears your problem.

---
Tags: opengl, glsl, lighting, normal-mapping, vulkan
---


# Question
Title: Things not appearing in front of canvas (follow up)
Follow up/related question to: Things disappear in front of Canvas

I'm having a very similar problem, where things are not appearing in front of my canvas. This time a particle system. I have tried the suggestions outlined in my previous questions (which worked then) but this time none of them will work:

You can see that the particle system is on top of the children and also I have added a canvas and overwritten sorting (the two suggestions in my previous post) yet the particles are not visible in front of the canvas.

# Answer
> 0 votes
For Particles, you need to alter the Renderer Sorting Order. Specify the sort order similar to the Canvas sort order, where you would like the Particles to be.

# Answer
> 0 votes
Divide your UI objects into two parts. Fixed background, gradient etc and HUD, Buttons, Popup etc.

Render fixed UI objects in a Camera screen space canvas. Render others in a Overlay screen space canvas. Scenes end up using multiple canvases usually.

Reset particle transform in inspector as you normally do for other objects.

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