# Question
Title: How to calculate 1st, 2nd, 3rd place and draw conditions in local multiplayer game?
I have a local multiplayer game with an end of round screen that pops up after each round. I'm trying to figure out the logic to calculate the 1st, 2nd, 3rd place from a maximum of 4 players. I also want draw/tie conditions. It's possible for 2 or 3 players to get the same score. The score is just an int for each player. I've been struggling with this for a while... Any help appreciated, even if its just some pseudo code to point me in the right direction. Also, I'd like to avoid using Linq if possible, as I've heard it doesn't play nice with Unity. Thanks

Edit:

Below is what I've managed to come up with for determining the draw conditions. Doesn't seem to hold up in all cases though... Surely there's a simpler approach?

```
         PlayerScore[] orderedScores = m_scores.OrderByDescending(ps => ps.score).Take(4).ToArray();

        _1stPlacePlayers.Add(orderedScores[0].playerNumber);

        if (orderedScores[0].score == orderedScores[1].score)
        {
            // 2 player draw 1st place
            _1stPlacePlayers.Add(orderedScores[1].playerNumber);
            if(orderedScores[0].score == orderedScores[2].score)
            {
                // 3 player draw 1st place
                _1stPlacePlayers.Add(orderedScores[2].playerNumber);
                if(orderedScores[0].score == orderedScores[3].score)
                {
                    // 4 player draw 1st place
                    _1stPlacePlayers.Add(orderedScores[3].playerNumber);
                }
            }else if (orderedScores[1].score == orderedScores[2].score)
            {
                // 2 player draw 2nd place
                _2ndPlacePlayers.Add(orderedScores[2].playerNumber);
                if (orderedScores[1].score == orderedScores[3].score)
                {
                    // 3 player draw 2nd place
                    _2ndPlacePlayers.Add(orderedScores[3].playerNumber);
                }
            }
            else if (orderedScores[2].score == orderedScores[3].score)
            {
                // 2 player draw 3rd place
                _3rdPlacePlayers.Add(orderedScores[3].playerNumber);
            }
        }

        else if (orderedScores[1].score == orderedScores[2].score)
        {
            // 2 player draw 2nd place
            _2ndPlacePlayers.Add(orderedScores[2].playerNumber);
            if (orderedScores[1].score == orderedScores[3].score)
            {
                // 3 player draw 2nd place
                _2ndPlacePlayers.Add(orderedScores[3].playerNumber);
            }
        }
        else if (orderedScores[2].score == orderedScores[3].score)
        {
            // 2 player draw 3rd place
            _3rdPlacePlayers.Add(orderedScores[3].playerNumber);
        }

```

# Answer
> 1 votes
Avoid looking at specific permutations with a branching tree structure of IFs and use a set-based definition of 1st, 2nd, 3rd that can handle arbitrary multiplicity. For example:

```
PlayerScore[] orderedScores = m_scores.OrderByDescending(ps => ps.score).Take(4).ToArray();
int[] uniqueScores = orderedScores.Select(ps => ps.score).Distinct().ToArray();
_1stPlacePlayers.AddRange( orderedScores.Where(ps => ps.score == uniqueScores[0] ).Select(ps => ps.playerNumber) );
if( uniqueScores.Length > 1 )
   _2ndPlacePlayers.AddRange( orderedScores.Where(ps => ps.score == uniqueScores[1] ).Select(ps => ps.playerNumber) );
if( uniqueScores.Length > 2 )
   _3rdPlacePlayers.AddRange( orderedScores.Where(ps => ps.score == uniqueScores[2] ).Select(ps => ps.playerNumber) );

```

I think you can simplify this down to a one or two-liner if you replace the hard-coded \_NthPlacePlayers collections with an indexable array of collections.

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


# Question
Title: How to check whether an angle lies within a specific negative to positive range?
I'm trying to develop a script that detects if an object's angles are tilting too much.

I am new to Unity, and I am sure this is not the best way to test an object's angles, but I am trying to learn C# so I'd rather figure that out myself.

All I want to know is how to check whether a value is between -101 and 101.

I have tried this so many different ways, and even though it is working fine for positive integers, the if statement is not applying the moment that my z angle becomes negative.

Here is what I have tried so far:

```
(maxangle = 101, minangle = -101)

if(Player.transform.rotation.eulerAngles.z > Mathf.Sign(-101) &&
Player.transform.rotation.eulerAngles.z < maxangle),

if(Player.transform.rotation.eulerAngles.z > minangle &&
Player.transform.rotation.eulerAngles.z < maxangle)

```

# Answer
Doing math on Euler angles can get you into trouble.

Under the hood, Unity uses quaternions to have simpler & more uniform rotational behaviour. It converts to Euler angles when it needs to display them in the inspector, but this conversion isn't unique. For instance, a z rotation of -5° is equivalent to a z rotation of +355°, and the engine might decide to give you the latter.

You can work around some common angular wraparound issues with the DeltaAngle method:

```
// This will wrap angles close to 360 around
// to the corresponding negatives instead
float difference = Mathf.DeltaAngle(0, transform.eulerAngles.z);

if(difference > minAngle && difference < maxAngle) {
    ...
}

```

This will behave well for rotations within a particular range, but the mapping from orientations to Euler angles has discontinuities, so you can get surprises if your object can take on any arbitrary orientation.

If what you want is to evaluate how much your object is leaning, comparing dot products of its local up or forward vectors can give you a more continuous and consistent measure, without the surprises of the arbitrary Euler angle mapping.
> 2 votes

---
Tags: unity, c#, euler-angles
---


# Question
Title: Update android game with new levels without replacing database
So I've published a game for android users containing 400 levels and 2k users have completed or are playing it since. Now I'm going to update the game with 600 levels, but I don't want current users to lose their info in database. I just want to add more levels to the database if it exists in their phone.

I'm using this code not to let database get replaced if it exists.

```
public DataService()
{

        const string databaseName = Constants.DbName;

#if UNITY_EDITOR
        var dbPath = string.Format(@"Assets/StreamingAssets/{0}", databaseName);
#else
        // check if file exists in Application.persistentDataPath
        var filepath = string.Format("{0}/{1}", Application.persistentDataPath, databaseName);

        if (!File.Exists(filepath))
        {
            Debug.Log("Database not in Persistent path");
            // if it doesn't ->
            // open StreamingAssets directory and load the db ->

#if UNITY_ANDROID
            var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + databaseName);  // this is the path to your StreamingAssets in android
            while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
            // then save to Application.persistentDataPath
            File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
                 var loadDb = Application.dataPath + "/Raw/" + databaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
#elif UNITY_WP8
                var loadDb = Application.dataPath + "/StreamingAssets/" + databaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);

#elif UNITY_WINRT
        var loadDb = Application.dataPath + "/StreamingAssets/" + databaseName;  // this is the path to your StreamingAssets in iOS
        // then save to Application.persistentDataPath
        File.Copy(loadDb, filepath);
#else
    var loadDb = Application.dataPath + "/StreamingAssets/" + databaseName;  // this is the path to your StreamingAssets in iOS
    // then save to Application.persistentDataPath
    File.Copy(loadDb, filepath);

#endif

            Debug.Log("Database written");
        }

        var dbPath = filepath;
#endif
        _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
       // Debug.Log("Final PATH: " + dbPath);

}

```

Also I've created a filed in database keeping database version to check what version the user has (like the version with 400 levels, the one with 600 levels or maybe more).

What I don't know is what is the best solution to add more records to an existing database. Has anyone got a solution?

# Answer
> 1 votes
The nice thing about SQL databases is that you can write data to them.

So instead of replacing the whole database, create an SQL script file with all the `INSERT`, `UPDATE` and `ALTER TABLE` statements you need to bring an existing database to the new version, add that script file to your package, and execute when the game is run for the first time after updating.

# Answer
> 0 votes
1) to insert Add in `dataservice.cs`

```
public Person Add_pwd()// gestion record tableau
    {
        var p = new Person
        {
            Util = control_text2.data1[0],
            Login = control_text2.data2[0],
            Pwd = control_text2.data3[0],
            Jour = date + " " + heure
         };
            _connection.Insert(p); //Update...
        return p;
    }

```

2)create table *YourTableName* in DB browser for *sqlite* 3)create `YourTableName.cs`

```
sing SQLite4Unity3d;
using System.Collections;
using UnityEngine;

public class Person  {

    [PrimaryKey, AutoIncrement]
    public int Id       { get; set; }
    public string Util  { get; set; }
    public string Login { get; set; }
    public string Pwd   { get; set; }
    public string Jour  { get; set; }

    public override string ToString ()
    {
        return string.Format ( "[ {0}\t{1}\t{2}\t{3} ]", Util, Login, Pwd, Jour);
    }
}

```

---
Tags: unity, android, databases
---


title: few button image are not updating

text:
# Question
Title: few button image are not updating
I am working on a game that contain 1000+ buttons starts from 0 - 999 with 3 decimals like 0-9, 00-99 and 000-999. if the user click the button the button image want to change. it working fine for me but the button with the name and Number(button name and button text both are same)50,100,200,300,400,...900 are not updating the ui. it showing an error like the object is destroyed but you are still trying to access it. but the button and the components in the buttons are not destroyed. i checked my code too.

```
        if (GameObject.Find (seatNo).GetComponent<UISetup> ()) {
            print ("Available");
        } else {
            print ("Not Available");
        }

```

here i tried to find the script is available or not. only for the buttons i mentioned above it's telling "Not Available". All others are working fine. but in the same time while running the game the script is available in the gameobject

I am calling the method from another script like this

```
        UISetup button = GameObject.Find (seatNo).GetComponent<UISetup> ();
        button.changeBtnBG ();
        button.valueUpdates (chip);

```

in UISetup.cs i use this code to change the Image Source

```
public Sprite RedSelectedImg;
public Sprite GreenSelectedImg;

public void changeBtnBG(){
    print ("<-------------select img changed-------------->");
    if (redBtn == false) {
        this.GetComponent<Image>().sprite = GreenSelectedImg;
    } else {
        this.GetComponent<Image>().sprite = RedSelectedImg;
    }
}

```

I am using unity 5.6.0. i don't know what's the error. Anybody please help. Thanks in Advance

# Answer
> 0 votes
Here you are using to call the number by integer. you are using 3 types of numbers like 0,00 & 000. so the button number like 010 would be consider as 10, 020 would be consider as 20. etc., so only the picture of the button is not updating. declare 10 game objects for the problem buttons declare it. check the number and change image for the game object.

---
Tags: unity, c#, game-design, monobehaviour
---


# Question
Title: game crash on android phone while using unity UI
I am trying to use an unity UI in my game. Initially I Created Canvas with all settings what I need then I compiled it on my phone its working perfectly. Inside the Canvas if I created any button or image means in editor its working fine but in android mobile the game get crash. I don't know what's happening?

Note: I already create the game with simple ui system. in that ui using box collider and listenerClicks() I handling all functions. Now i am trying to convert this system to Unity UI system.

Here my Logcat

I am using Unity 5.2, c#

# Answer
> 0 votes
it's a problem in unity version. after update my unity the problem got fixed.

other case if we click reimport all options it may fix.

---
Tags: unity, gui
---


# Question
Title: Fair monetization of a MMO with a simulated economy
I am in the design phase of a MMO game based around flying age-of-sail airships. Players will be able to captain their own ship (owned by their in-game nation or faction or themselves if they become sufficiently wealthy), or play as a crewmember on their own or another ship in battle , or as ground defence personnel when their own ship becomes too boring.

The players might also design or redesign the flying sailing ships (and later, as technology progresses, flying steam or diesel ships), and test new ship design, or plan ground defences.

All of this would be based around a simulated economy, where resources are produced, shipped and either consumed or lost to make value-added foods, commodities, communities or vessels. In a war, commerce raiding should - eventually - have an impact as much as direct military action against enemy troops and vessels.

Players could be merchants, pirates, smugglers, privateers, naval captains, or just another member of a ship's crew. Players could also design airships and ground defences, and contribute to the governance of their province.

So, for all of this, how can I monetize this game? I need to consider startup capital, but more importantly, it needs to make a profit.

However... I don't want to fall into the ways of many games with micro-transactions. That means no pay-to-win - a paying player must have only their own skills and equipment to help them win against a free-to-play player... *if* I go with that method.

The economy is simulated, and I would like the method of monetization to have a minimal impact on that, but not necessarily *no* impact. Players must know exactly what they are spending their in-game currency upon, an must be able to sell for in-game or possibly even real currency any 'physical' game object - with a cut to the broker (i.e. the developer).

I have considered an up-front cost, but that alone does not guarantee an income stream as the player base becomes saturated. I have considered instant IAP of objects that would otherwise take time to produce - the player buys them from the developer's nation. I have considered allowing a certain amount of free screen time per month, extendable by a purchase.

What methods would guarantee continual income for a number of years at least, without unduly upsetting players who may be wary of traps such as loot chests or pay-to-win? Can a game such as this be funded prior to the commencement of development?

# Answer
> How can I monetize this game?

Traditionally, there are four methods to monetize an MMO:

* **Buy the game, play forever.** In this model you will get a lot of capital on release, but then you won't have a constant cash flow anymore. But if you want to keep the servers running and the community happy, then you will need some regular income. That means you will have to regularly release paid expansions for extra money. If you design these expansions in a way that they are optional, then you will end up fragmenting your playerbase. If you design the expansions in a way that they are quasi mandatory, it will feel to the players like a stealth subscription fee.
* **Subscription based**. Take a monthly fee for playing your game. This used to be the standard model for MMOs in the 2000s. It seems very attractive, because it promises you a constant, reliable cash flow. But unfortunately gamers don't really seem to like this model anymore. Many gamers don't want to commit to a subscription and prefer the "free to play with optional microtransactions" model. Those who are willing to commit, prefer the "pay once" model.
* **Pay to win**. Microtransactions can indeed be very unethical by doing stuff like selling raw power ("Double PvP damage potion"), intentionally adding features which make your game less fun and then take money to remove those features ("wait two hours or pay now to continue playing immediately") or exploiting gambling addiction ("loot boxes"). But players have learned to recognize these strategies and publicly shame games which use them, which drives away potential players. So this unethical monetization model doesn't work that well anymore.
* **Free to play done right**. But there is also a different way to do microtransactions. Many MMO games are extremely successful lately with a far more ethical microtransaction model:

+ Make sure that anything which actually affects gameplay can also be obtained through regular gameplay.
    + Never sell power! Anything buyable with gameplay effect should be a tradeoff, not an upgrade. The buyable content should make the game more interesting by adding more variety, but not give a true advantage.
    + Don't base your monetization design on the premise that every player should eventually become a paying player or leave. The "freeloaders" are extra content to entertain the paying ones. Don't treat them as undesirables.
    + Charge what you want for purely cosmetics stuff. Everyone wants to look cool and unique in an MMO and they are willing to pay for it.

For further watching I recommend the video series about monetization from the renowned game design YouTube channel *Extra Credits*.

> Can a game such as this be funded prior to the commencement of development?

If you don't have any capital on your own, there are two ways to fund the development of a larger game:

* **Venture capital**. Find someone rich who is willing to invest into your project in exchange for a cut of the future profits. This requires that you have a convincing plan and the necessary references to convince the investor that you have the skills and commitment to pull it off. It also might restrict your creative freedom, because investors can rarely be convinced to not meddle with your design decisions.
* **Crowd funding**. Get people excited about your game and get them to pay upfront years before the game is finished. There was quite a crowd funding boom in the past years which resulted in some awesome games being made. However, this has recently become more difficult. That's because there were also several high-profile projects which ended up in disappointments, got cancelled or even outright stole the money and ran away (for some examples, check the "Kickscammers" series by Larry Bundy Jr. and Dan Ibbertson on YouTube). So possible backers have become a lot more careful lately. If you want to run a successful crowd funding campaign, then you need:

+ An interesting game concept which has the potential to excite a lot of people. This might either be something new and innovative or something which covers an underrepresented niche.
    + A prototype with production-ready assets so you can show people some footage of what you are up to.
    + A way to convince people that you have the skills and resources to complete the project. The best way to do that is by pointing out that you were involved in several successful game development projects in the past.
    + A very, **very** good PR strategy so people notice your campaign. Just getting listed on a crowdfunding platform won't get you any backers. You are responsible for promoting it.

If both of these models seem too far away for you, then consider what you can do with the resources you have available on your own. Think smaller. Create a simple game first which you can create in your spare time while working a regular job which pays your rent. Collect experience, build a core fan base and ideally a meager income which can then fund a more ambitious project.

I wish you the best of luck with your project and I am looking forward to playing it.
> 9 votes

---
Tags: mmo, monetization
---


# Question
Title: How do I load a specific Asset Bundle Manifest, but not the Asset Bundle itself?
I have a bunch of Asset Bundles. I load the generic Asset Bundle Manifest to get the names of all of my asset bundles. I want to load only a specific asset from the bundle, but I need to retrieve the names of the assets so I can choose which one. The names of these assets are in the asset bundles manifests associated with each asset bundle.

How can I load just the manifest for a particular asset bundle?

This is the closest I have come, but it does not work:

```
private IEnumerator LoadAssetNames()
{
    foreach (var bundleName in assetBundleNames)
    {
        string url = "my://server/" + bundleName + ".manifest";
        var www = UnityWebRequest.GetAssetBundle(url);
        yield return www.Send();
        if (www.isError)
        {
            Debug.LogError(www.error);
            yield break;
        }
        var bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;
        www.Dispose();
        assetNames[bundleName] = bundle.GetAllAssetNames();
    }
}

```

It returns to me a failed to decompress error:

```
Error while downloading Asset Bundle: Failed to decompress data for the AssetBundle 'my://server/bundleName.manifest'.

```

I can download the manifest directly as a string or set of bytes, but then how can I cast it to an `AssetBundleManifest`?

# Answer
Not sure if this is relevant or not any more but loading a manifest- according to Unity's docs requires loading the bundle and then grabbing the manifest.

```
string url = "my://server/" + bundleName

```

Instead of

```
string url = "my://server/" + bundleName + ".manifest"

```

Using AssetBundles
> 1 votes

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


# Question
Title: Error:d1 was not declared in this scope; How to fix this error in c++?
```
#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;
class cowboy
{

public:
    int life;
    int player;
    int maxatk;
    int minatk;
    int type;
    cowboy()
           {

           }
    cowboy(int v, int am, int an, int t)//it is an constructor which is a function that will let us assign the four variables in a single instruction when the cowboys is created
       {
        life=v;
        maxatk=am;
        minatk=an;
        type=t;

        }

};
void duel();

int main()
{
    duel d1;
    d1.mainmenu();
    system("pause");
    return 0;
}
class duel
{

public:
    duel()
    {

    }
    void mainmenu()
    {
        int choice;
        do
        {
            cout<<"main menu\n";
            cout<<"1-play\n";
            cout<<"2-history\n";
            cout<<"3-exit\n";
            cin>>choice;
            if(choice==1)
            {

            }
            else if(choice==2)
            {

            }
        }
            while (choice!=3)

            }

void selectcowboy()
{

     cout<<"select your cowboy\n";
     cout<<"1-Basic\n";
     cout<<"2-resistence\n";
     cout<<"3-fast cowboy\n";
     cout<<"choose";
     int choice;
     cin>>choice;
     cowboy player;
     cowboy machine;
     if(choice==1)
     {
         player.life=30;
         player.maxatk=15;
         player.minatk=8;
         player.player=1;
         player.type=1;

     }
     else if(choice==2)
     {
         player.life=50;
         player.maxatk=15;
         player.minatk=8;
         player.player=1;
         player.type=2;

     }
    else if(choice==3)
    {
        player.life=28;
        player.maxatk=9;
        player.minatk=5;
        player.player=1;
        player.type=3;

    }
    int rival=rand()%3+1;
    if(rival==1)
{
    machine.life=30;
    machine.maxatk=15;
    machine.minatk=8;
    machine.player=1;
    machine.type=1;

}
else if(rival==2)

{

    machine.life=50;

machine.maxatk=15;
machine.minatk=8;
machine.player=1;
machine.type=2;
}
else if(rival==3)
{

    machine.life=28;
    machine.maxatk=9;
    machine.minatk=5;
    machine.player=1;
    machine.type=3;

}
else
{
    cout<<"error"<<choice<<endl;

}
//incia el dueolo
cout<<"\n preparing duel\n";
cout<<"player life"<<player.life<<"machine life"<<endl;
cout<<"duel starts now"<<endl;
bool s=true;//bool variable is used to find whether it is your turn or not
while(true)
{
    if(s==true)
    {
        player.minatk+player.minatk        ;

    }
    else
    {
        machine.minatk+machine.minatk;

    }
    cout<<"player's remaining life"<<player.life<<"\n";
    cout<<"machine's remaining life"<<machine.life<<"\n";
    if(player.life<=0)
    {

    }
    else if(machine.life<=0)
    {

    }
    if(s==true)
    {

    }
    else
    {

    }

}
    }
    void story()
    {

    }
};

```

# Answer
You can not declare a variable of class `duel` before introduing it. So you need to move the `main()` method below the `duel` class definition:

```
class duel
{
...
};

int main()
{
   duel d1;
   ...
}

```

By the way, it would be better to keep your classes in separate files, i.e., create `Duel.h` and `Duel.cpp` files and move the implementation of `Duel` class to them. Then \`#include "Duel.h" in your main c++ file.
> 1 votes

# Answer
Your main function cannot find a declaration for the object `duel`.

To fix this you have to move your `main()` function at the bottom of your file (or at least after every class, struct or function has already been defined)

```
class duel
{
     //...
}

int main()
{
    duel d1;
    d1.mainmenu(); // this works
    // rest of your code
}

```
> 0 votes

---
Tags: c++
---


# Question
Title: Most efficient way to remove a Rectangle ? Monogame/XNA
I have a project in which I'm trying to remove the "collision box" (Rectangle class) of one of my enemy. My game logic basically is:

```
foreach (Enemy e in Enemy.enemiesOnScreen) {
            if (e._isDead) {
                e._collisionBox = new Rectangle(0, 0, 0, 0);
            }
            else {
                e.Update(gameTime);
            }
        }

```

What I wrote works perfectly, but wouldn't that be subject to memory overflow (for a much higher number of instances) or bad optimization in a real game project ?

# Answer
Since the Rectangle class is a struct, all the storage memory allocation is already done. In this case, assigning the 0, 0, 0, 0 values to my rectangle to "remove" it from the scene is FINE and will not cause any memory / optimization issues in a much bigger project with much more instances.

Althought I found a better alternative which is :

```
e._collisionBox = Rectangle.Empty;

```

Easier and more readable code. Still don't know if this is the best option in this situation but, I'll be fine with that.
> 1 votes

---
Tags: xna, sprites, monogame, optimization
---


# Question
Title: How do/should MMOs handle disconnection during PvP?
In an MMO (not even necessarily an MMORPG) what are some techniques for dealing with players disconnecting in the middle of PvP?

In particular - how do you avoid adversely affecting people who get disconnected due to network (or even real-life) issues, while not adversely affecting those people that are engaging them?

And, importantly, how do you ensure that disconnecting cannot be used as a method of cheating?

# Answer
We had this problem with some online CCGs that I worked on. Best solution I've seen:

1) Players MUST connect to the server, not to each other directly, and you should NEVER pass IP addresses of opponents in the data you stream to the players. This prevents denial-of-service attacks where a player forces their opponent offline for the win.

2) Dropped connection = you lose, opponent wins. We must assume that if you dropped, it was a drop to avoid certain loss.

3) Disconnects attempt to reconnect for a period of time, so that a slight net hiccup doesn't force you to lose through no fault of your own. Ideally, the time is long enough to allow someone to reconnect if they accidentally kicked the cable, but short enough that the opponent doesn't get frustrated and fall asleep while waiting. I think we found about 45 to 60 seconds felt right.

4) Allow players to report their opponents. This is a necessary catch-all to prevent anyone finding some annoying way around your policy. Like, maybe being so verbally abusive that the opponent drops just to get out of there, or continually disconnecting and reconnecting to stretch the game length, or stonewalling to avoid a loss, or whatever. You can't stop ALL bad behavior, but you can include an in-game mechanism to report it, and then let your customer support department handle the rest.
> 14 votes

# Answer
Popular MMORPG RuneScape uses a 1 minute timer. When you disconnect, your character remains in the world for a full minute, vulnerable to attacks and what not.
> 13 votes

# Answer
I had to tackle this problem once in an online racing game where players who were losing would often turn off their consoles to avoid the loss appearing on their records. However it applies very well for any PvP situation.

My solution went like this:

1. At the beginning of the match, once all the players have joined and play is about to begin, calculate what the outcome would be if our player loses the match. In our racing game, 'lost' means 'came in last place' and the usual outcome would be 'minus N points from the players rank'.
2. Save the outcome to a secure location (Savegame, leaderboard, Online data area, etc).
3. Along with the outcome, store a 'GameStarted' flag. This just signifies that the game has begun. We'll need it later on.
4. When the game completes, calculate the actual outcome and apply it to the players score/stats. Unset the 'GameStarted' flag. This is the normal game-completion process.
5. However, if the player disconnects, pulls his cable or powers off, eventually they'll return back to the games menu. In the menu code, we do a check for the 'GameStarted' flag. If it is set, we're sure that we've detected an in-game disconnection from earlier. We can then apply the stored outcome to the players score/stats. It will be the same as if the player lost the game. It's also a good idea to put up an alert informing the player of what's happening. Then, once he sees that there are consequences for disconnecting mid-game, you'll see that behaviour start to change.
> 8 votes

# Answer
I think the only way to pull this off would be a matter of the structure of your game. Theres' two ways to make cheating less desirable: punishment or reward. So if you don't want adverse punishment think of ways to reward the player who didn't drop.

Instead of the reward from PvP being the loot of the conquered's body (which makes dropping a very bad thing) make winning bestow some reward like exp., gold, or something else entirely (Points? Ranking?). If one of the players is kicked off then the remaining player receives the reward and the player who was kicked off gains nothing but loses nothing. Unless it's a ranking system in which case the player leaving might lose some ranking points.
> 5 votes

# Answer
Lineage II does it like this:

* You can't exit the game client during a fight - any fight starts, no matter if you attacked, got attacked or healed a team mate who's fighting and you are in "fighting stance", which lasts for 15 seconds after the last such action was made.
* If you disconnect anyway or your game crashes, your character stays in the game for those 15 seconds before disappearing. It even continues auto-attacking whatever it was attacking, but not using skills - same as it would if you went AFK.
* There *is* a way to disconnect instantly, however, by reconnecting to the same account with another client. This is regarded as borderline cheating by the community when done in PvP, and some cheat tools have an option to use it as well, so it isn't being used much there. When biting too much to chew in PvE however, some people still use this trick to avoid unnecessary deaths (though there are in-game items which allow almost the same, namely the "blessed scrolls of escape").
* Reconnecting to a PvP-flagged zone (castle ground during a siege, for example) and some specific non-instanced epic boss areas moves the character to the nearest town (safe zone) instead. Thus, disconnecting there to avoid "losing" carries a penalty for your team, which means it is strongly discouraged by the social norms of the game.

Personally, I would do it similarly, only allow the players to pre-define the actions their character is taking on disconnection (stay and fight, run to the nearest safe zone avoiding aggro, use a regular scroll of escape, use a blessed scroll of escape, ...) and have the characters persist in the game world even if the player isn't logged in.
> 5 votes

# Answer
The one who disconnected will die once he gets stabbed enough, and the other one will be credited for the kill. Anything more lenient will be exploited.

Generally there's a 1- to 5-minute timer before your body leaves the world.
> 3 votes

# Answer
There is no way to determine what caused the disconnection (did the power go off? did I rage throw my machine against a wall?), so you can only assume that the user is trying (or would try) to cheat and make them vulnerable for X minutes.
> 3 votes

# Answer
The way this is handled by EVE Online is as follows:

* Ship starts to engage warp 15 seconds after disconnect. If it is warp scrambled the ship will not warp away. (Your character's ship will start to "run away" after 15 seconds, unless it is "trapped" by another player)
* PVP timer (time until player "runs away" while engaged in PvP combat) is set to 3 minutes. (This is to counter a number of other timers).
* NPC timer stays at 1 minute, but ship warps away after 15 seconds unless warp scrambled by NPC.
* When a ship is target locked by player, it should switch to the pvp timer (to counter it using the 1 min timer if it disconnects under circumstances where it isn't targetable until the timer is set).
> 3 votes

# Answer
If you have a way of modeling the players usual patterns in battle you could send them into an AI mode until they reconnect or the battle is over whichever comes first. But don't give them any rewards (exp, items, etc.) for the battle unless they return in X amount of time.
> 2 votes

# Answer
I'd implement some sort of hysteresis. You can use the carrot and the stick. But picking which to use can be based on track record (you could also do an analysis of their connection and current "win-ability" and use that.). It's how you'd do it in-person hopefully. Simple model:

* If I'm "bad" and I DC I get the stick. I am now more bad.
* If I'm "bad" and I complete I don't get the stick but I also don't get the reward. I am now closer to being good.
* If I'm "good" and I DC I don't get the stick but I also don't get the reward. I am now more closer to being bad.
* If I'm good and complete I get the reward. I am now more good.

You can abuse it yes. But doing so might take more effort than just biting the bullet. (If it took 2 DCs to be bad for example you could technically get rid of half of your losses. But it does mitigate *some* abuse and in the case of less than clever players *all* abuse).

Granted using this means the scoreboards won't sum to 100%. Since you can DC while good and not record a loss. But the other good player can record a win. Also not summing to 100% means 2 players can cooperate switching off DC player to stack wins.

So not foolproof, but added Bayesian analysis of gamestate+connection could probably detect funkiness and make this scheme bulletproof. (You can defeat Bayesian analysis but humans aren't good at doing this and the math is out of reach for most people, not to mention the time investment to "prime" a fight to get through with DC being okay).
> 0 votes

---
Tags: game-design, networking, mmo, balance, pvp
---


# Question
Title: Difference between texture.Load and texture.Sample(PointSampler,..) in HLSL/Dx
Conceptually, I understand the difference between load and sample but I want to know if essentially point sampling and load do the same thing when it comes to selecting a texture value (ignoring an out of bound situation).

# Answer
Point sampling goes through the texture sampling hardware on your GPU, meaning that it obeys rules for how to handle "between texel" cases (in this case take the nearest neighbour) and may be subject to leeway in the specifications for driver-dependent or GPU-dependent behaviour. You feed it with normalised (0..1) texture coordinates, and it also respects other sampler states that may be set: mipmapping, LOD, wrap or clamp modes, etc.

Loading bypasses the sampling hardware and just loads directly from the source texture. No other sampler states will apply.

So no, they're not the same.
> 1 votes

---
Tags: textures, directx11, hlsl
---


# Question
Title: Unity Surface Shader Using "worldNormal" While modifying Normals Turns Shader Black
So I was writing a simple triplanar mapping shader and while doing so encountered a bug where when using `IN.worldNormal` in code while writing to `o.Normal` would result in the albedo turning black as can be seen below: https://ibb.co/n1DHC8
Here is the complete shader code (bug tested on webGl as well as Windows DX11):

```
Shader "Custom/NormalMappedTest" {
Properties {
    _Color ("Color", Color) = (1,1,1,1)
    _MainTex ("Albedo (RGB)", 2D) = "white" {}
    _NormalMap("Normal Map", 2D) = "bump" {}
    _Glossiness ("Smoothness", Range(0,1)) = 0.5
    _Metallic ("Metallic", Range(0,1)) = 0.0
}
SubShader {
    Tags { "RenderType"="Opaque" }
    LOD 200

    CGPROGRAM
    // Physically based Standard lighting model, and enable shadows on all light types
    #pragma surface surf Standard fullforwardshadows

    // Use shader model 3.0 target, to get nicer looking lighting
    #pragma target 3.0

    sampler2D _MainTex;
    sampler2D _NormalMap;

    struct Input {
        float2 uv_MainTex;
        float2 uv_NormalMap;
        float3 worldPos;
        float3 worldNormal; INTERNAL_DATA
    };

    half _Glossiness;
    half _Metallic;
    fixed4 _Color;

    // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
    // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
    // #pragma instancing_options assumeuniformscaling
    UNITY_INSTANCING_BUFFER_START(Props)
        // put more per-instance properties here
    UNITY_INSTANCING_BUFFER_END(Props)

    void surf (Input IN, inout SurfaceOutputStandard o) {
        // Albedo comes from a texture tinted by color
        fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;

        //Even just having this here causes the bug
        float3 wnrm = abs(normalize(IN.worldNormal));

        float3 nrm = UnpackNormal(tex2D(_NormalMap, IN.worldPos.xz));

        o.Albedo = IN.worldNormal;// c.rgb;
        o.Normal = nrm;
        // Metallic and smoothness come from slider variables
        o.Metallic = _Metallic;
        o.Smoothness = _Glossiness;
        o.Alpha = c.a;
    }
    ENDCG
}
FallBack "Diffuse"
}

```

Any help would be appreciated, thanks in advance, \- Thomas

# Answer
It's a bit frustraiting. According to Unity Manual Input structure section you have to use WorldNormalVector (IN, o.Normal) instead of IN.worldNormal if you are writing to o.Normal
> 1 votes

---
Tags: unity, shaders, normals
---


title: Object doesn't instantiated right spot

text:
# Question
Title: Object doesn't instantiated right spot
I have weird glitch in my game. When player shoot the gun, bullet is instantiated something called "ShootPoint" transform.

This is the ShootPoint's position:

And this is the code of firing bullet:

```
RigidbodyProjectile CreateBullet() {
    GameObject bullet = Instantiate(bulletPrefab, shootPoint.position, shootPoint.rotation);
    RigidbodyProjectile projectile = bullet.GetComponent<RigidbodyProjectile>();

    projectile.rigidbody.AddForce(shootPoint.forward.normalized * bulletSpeed, ForceMode.VelocityChange);

    return projectile;
}

```

Simple script to just instantiate bullet prefab in ShootPoint.transform.

However when I run the game, bullet generated totally wrong place:

That picture captured right after creation, even before push the bullet. Here's the updated code for capture that moment, I intentionally throw the error so that makes game stop:

```
RigidbodyProjectile CreateBullet() {
    GameObject bullet = Instantiate(PrefabManager.GetPrefab("bullet"), shootPoint.position, shootPoint.rotation);

    // Throw the exception
    throw new System.Exception("DIE");

    // So codes under here will not work
    RigidbodyProjectile projectile = bullet.GetComponent<RigidbodyProjectile>();

    projectile.rigidbody.AddForce(shootPoint.forward.normalized * bulletSpeed, ForceMode.VelocityChange);

    return projectile;
}

```

I don't get it, why my bullet doesn't generated in ShootPoint.transform? I literally removed all components in Bullet and tried again but still had same problem.

Funny thing is that this is not always happening, it only happens in certain angles, especially looking down. I already checked hundreds that ShootPoint pointing something wrong direction or reference of ShootPoint was wrong, but no, there was no problem at all!

What should I check in this case? It's really annoying issue, because when I shoot little lower angle, it always hit the ground almost instantly after fire.

Anyone who knows about this issue, if could be great what should I check, thanks.

\** Additional Info about Bullet \** I forgot to mention about bullet. It has parent and child, and parent has rigidbody and child has mesh to display. This is because basically bullet wasn't pointing forward so I rotated it to pointing forward and wrapped by empty game object so that eventually it pointing forward direction even mesh is rotated.

Here's the screenshot to explain this:

# Answer
> 0 votes
I solved this problem, but still don't get it why it happens. If someone know why this happens, could be very helpful with share your information!

Anyway as I mentioned in my question, Bullet object has child object, which is actual object that renders "bullet" mesh. This is because bullet mesh doesn't pointing forward, so I wrapped the bullet mesh and rotated, so the bullet pointing forward without rotation. Also parent object has rigidbody.

However in this game, I'm using Raycast to hit detection because the bullet is really high speed projectile and collider doesn't working well, it just passing through the objects.

But when I was assemble and tested the bullet, I added Mesh Collider into child object. Of course, I turned off that mesh collider after changing colliding logic to using Raycast instead, however, some reason, my problem solved by removing this **deactivated** mesh collider.

Now bullets spawning correct position, everything works well, but still don't get it why **deactivated** collider produced this issue.

Anyway if someone facing the similar problem like me, make sure your child object has **unusing** collider in it. Regardless it's activated or not, it seems like it's affects in physics system.

I hope someday, someone explain this issue with more detail.

---
Tags: unity
---


title: Collision detection in 2D games

text:
# Question
Title: Collision detection in 2D games
I am making a basic 2D platformer. I want to get the *relative position of one rectangle to another*.

This is how I do it right now:

```
const float offset = 5;
if (x1 <= x2 && x1 + w1 >= x2)
            {
                if (Math.Abs(y1 + h1 - y2) <= offset)
                    return CollisionType.Top;
                else if (Math.Abs(y1 - h2 - y2) <= offset)
                    return CollisionType.Bottom;
                else if ((y1 <= y2 && y1 + h1 >= y2) || (y1 >= y2 && y1 <= y2 + h2))
                    return CollisionType.Left;
            }
            if (x2 <= x1 && x2 + w2 >= x1)
            {
                if (Math.Abs(y1 + h1 - y2) <= offset)
                    return CollisionType.Top;
                else if (Math.Abs(y1 - h2 - y2) <= offset)
                    return CollisionType.Bottom;
                else if ((y1 <= y2 && y1 + h1 >= y2) || (y1 >= y2 && y1 <= y2 + h2))
                    return CollisionType.Right;
            }

            return CollisionType.NoCollision;

```

Here how this function works (or at least how I suppose it to work):

Using this function, I often have *collision bugs*, but I cannot understand a global rule of when it happens. I don't think that a bunch of `if` blocks would solve the problem.

**I need a collision detection function that receives two arguments of type `Entity`** (The class can contain any fields or functions, but it must have an X, a Y, a Width and a Height) **The function needs to return the *relative* position of the first rectangle to the second.**

**What improvements would you suggest to my current function** or **is there a better system for collision detection in 2D games where one needs to get a *relative position* instead of a simple `true false`?**

# Answer
> 1 votes
The simplest way is not to check if there is a collision but rather to check if its impossible for there to be a collision.

To do this you need to verify if the two sides that would overlap in a collision are too far away form each other for that to be impossible:

```
if(Obj1.Right < Obj2.Left
   || Obj1.Bottom < Obj2.Top
   || Obj1.Left > Obj2.Right
   || Obj1.Top > Obj2.Bottom){
    //There is a collision
}

```

Using this technique you save on a fair bit of computation when there is no collision because once one of the tests fail it doesn't bother doing the rest since there is no point. Do note though that this version counts barely touching as a collision, so you may want to switch out some \> and \< with \>= and \<= to have tighter collision checking if that is what you require

# Answer
> -2 votes
You should compare the distance between the opposite sides of both squares and the side which has the smallest distance should be returned. I have written some pseudo code u can get inspired by. The long method/function names are just to make it very clear what they do.

```
CollisionType GetCollisionTypeFraSquare2ToSquare1(x1,y1,x2,y2)
{
    distTop = Math.abs( y2 + h2- y1 )
    distBottom = Math.abs( y1 + h1 - y2 )
    distRight = Math.abs( x1 + w1 - x2  )
    distLeft = Math.abs(x2 + w2 - x1 )

    if( IsFirstNumberSmallest(distTop,distBottom,distRight,distLeft) )
        return CollisionType.Top;

    if( IsFirstNumberSmallest(distBottom,distTop,distRight,distLeft) )
        return CollisionType.Bottom;

    if( IsFirstNumberSmallest(distRight,distTop,distBottom,distLeft) )
        return CollisionType.Right;

    if( IsFirstNumberSmallest(distLeft,distTop,distBottom,distRight) )
        return CollisionType.Left;

    //If nothing has been returned yet it means there are 2 distances which are the same.
}

bool IsFirstNumberSmallest(n1, n2, n3 ,n4)
{
    return n1 < n2 && n1 < n3 && n1 < n4;
}

```

---
Tags: 2d, collision-detection
---


# Question
Title: What does vertex:disp and tessellate:tessEdge mean? [Shader] [Unity]
I came across the following declaration on unity tutorial

```
#pragma surface surf BlinnPhong addshadow fullforwardshadows
vertex:disp tessellate:tessEdge nolightmap

```

I think disp is the displacement shader but what does `vertex:disp` mean? Likewise for `tesselate:tessEdge`.

from https://docs.unity3d.com/Manual/SL-SurfaceShaderTessellation.html

Thanks. I am rather new to HLSL.

# Answer
**Vertex shader**

> It is possible to use a “vertex modifier” function that will modify the incoming vertex data in the vertex Shader. This can be used for things like procedural animation and extrusion along normals. Surface Shader compilation directive vertex:functionName is used for that, with a function that takes inout appdata\_full parameter.
>
> https://docs.unity3d.com/Manual/SL-SurfaceShaderExamples.html

your vertex modifier function named `disp`.

so `vertex:disp` mean that your `vertex` will use `disp`:

```
void disp (inout appdata v)
{
float d = tex2Dlod(_DispTex, float4(v.texcoord.xy,0,0)).r * _Displacement;
v.vertex.xyz += v.normal * d;
}

```

**DX11 Tessellation**

This controls how many subdivisions you want to split your triangles into. (Note that DirectX is Windows only, requires a DX11 GPU and has to be enabled in Unity)

so `tesselate:tessEdge` mean that your `tesselatation` will use `tessEdge`:

```
float4 tessEdge (appdata_full v0, appdata_full v1, appdata_full v2)
{
return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, _EdgeLength);
}

```

If you want to understand tesselatation use `Shading Mode > WireFrame` then move around your object that has this shader:
> 1 votes

---
Tags: unity, shaders, hlsl, cg
---


# Question
Title: Creating a letterbox screen for Android devices
I want that the screen looks the same on every Android device without distorting the sprites.

One player should not see more of the map than another player just because they have a bigger screen or different resolution on their device.

I use (1334, 750) as my virtual resolution and only landscape mode is supported. But at the moment, you can see more of the map on top and on the bottom if you have a device with different aspect ratio.

How would I create a letterbox on top and on the bottom so that the visible game window keeps the same aspect ratio and portion of the game world visible on every device?

Do I need to modify my 2D camera when I create a letterbox screen?

At the moment it looks like this:

But it should look like this so that everyone can see the same map on the screen:

```
 public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Camera camera;
        Vector2 vp, gameWorldSize = new Vector2(1334, 750);
        float ScaleX, ScaleY, Scale;
        Vector2 Newcameraposition;
        Texture2D Background;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.IsFullScreen = true;
            graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Background = Content.Load<Texture2D>("background");
            vp = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
            ScaleX = vp.X / gameWorldSize.X;
            ScaleY = vp.Y / gameWorldSize.Y;
            Scale = Math.Min(ScaleX, ScaleY);
            camera = new Camera(new Vector2(gameWorldSize.X / 2, gameWorldSize.Y / 2), Scale, vp);
        }

        protected override void Update(GameTime gameTime)
        {
            Newcameraposition = new Vector2(gameWorldSize.X / 2, gameWorldSize.Y / 2);
            camera.Update(gameTime, Newcameraposition, Scale, vp);

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.GetMatrix());
            spriteBatch.Draw(Background, new Rectangle((int)gameWorldSize.X / 2, (int)gameWorldSize.Y / 2, Background.Width, Background.Height), null, Color.White, 0, new Vector2(Background.Width / 2, Background.Height / 2), SpriteEffects.None, 0.0f);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

```

My 2D camera:

```
 public class Camera
    {
        public Vector2 PlayerPosition;
        private Vector2 Viewport;
        private float Scale;

        public Camera(Vector2 playerposition, float scale, Vector2 viewport)
        {
            PlayerPosition = playerposition;
            Scale = scale;
            Viewport = viewport;
        }

        public void Update(GameTime gameTime, Vector2 playerposition, float scale, Vector2 viewport)
        {
            PlayerPosition = playerposition;
            Scale = scale;
            Viewport = viewport;
        }

        public Matrix GetMatrix()
        {
            return Matrix.CreateTranslation(new Vector3(-PlayerPosition.X, -PlayerPosition.Y, 0))
         * Matrix.CreateScale(Scale, Scale, 1)
         * Matrix.CreateTranslation(Viewport.X / 2, Viewport.Y / 2, 0);
        }
    }

```

# Answer
> 0 votes
You have two options in my view:

1. **Stretching** (Bad): I have no idea about the engine you're using (if any), but I'm pretty sure in every modern render engine there's an option for handling multi-resolution. For instance, in V-Box and Cocos2d-x engines you have the `Exact fit` option for that.
2. **Fog of War**: As you mention, you can put some opaque element around the must-be-visible. I wouldn't touch `Camera` as it's not a camera-issue, instead, a *game-design decision*. The nature of the problem is the same in many games which the map shouldn't be shown unless the player discovered it by moving there.

I don't know the framework you're using, but I think you need to modify `Draw()` method and in the most simplified version draw for black rectangle, like:

---
Tags: c#, android, monogame, aspect-ratio, xamarin
---


# Question
Title: Read function outside of code while run-time?
Hi it is my first post on this community. So if i was rude or something please let me know :)

So I just started learning game development alone. It's been about 1 year since I begin to learn c and c++. Recently I started planning to make a game for my own entertainment and future career.

I'm trying to make the game as mod-friendly as possible. So I thought that I should make abstract classes that have most of the functions for working on run-time. Then when the game starts, the system reads mod files for filling out class information and stores that base object in some data storage made with a singleton(for easy access). And, then use a factory pattern(I hope I'm using it right) to copy the base object that I need, fill it with basic information and store it in the object storage.

The problem is, I can't figure out how I can make it so each object from each mod file acts with its own behavior.

For example: Core mod(main game) has an abstract class named 'living entity' 'Living entity' has some information like bone structure type, mesh name, entity size, etc... And a mod file from the core mod makes a 'human' class that has information for 'human bone type','basic human','human size' etc The human class does not need any special functions because it only uses basic functions that the game provides.

But modder A wants to make a Vampire entity. Vampire will have information like a human. So modder A fills up or copies the 'human' file and edits the class id value with which the system identifies objects and uses as a name. Vampire needs new skills, health effects and custom death(leaves an ash pile instead of a corpse) The game also has skills and health effects as a kind of component or class. So modder A fills up information but one of the skills has a unique projectile effect or one of the health effects has a unique behavior that the game does not provide So modder A wants to override projectile or health functions only for the vampire's unique skill or health

In this case how would I support them to override functions for their own needs? One of my idea was to read the dll and store function pointers in data storage and put the code on a base abstract object and then call it if the object has a custom function. But I am not sure this works and that it is how people do it. So if there is some kind of information or documentation for that please let me know I'm arguing with this problem about month D;

# Answer
> 0 votes
If you want to allow modders to not just inject data but also code into your game, then there are two appoaches:

* Have your game load **dynamically linked libraries** (`.dll` on Windows, `.so` on UNIX) at runtime and execute functions with certain names in them. This allows modders to create mods in C++ or any other programming language which can be used to build libraries. However, there are two downsides. First, these libraries must be compiled for the users target architecture, so mods won't be cross-platform unless people recompile them for every platform your game supports (but that's of course only a problem if your game is cross-platform in the first place). But a second and even greater problem is security. These libraries can do anything you can do in C++, so it would be possible for malicious people to spread mods which contain malware.
* Add an interpreter for a **scripting language** to your game. That way mods can contain scripts which are executed by your game and can be used to implement custom behavior. The advantage over the library method is that scripts can be properly sandboxed. You can decide what functionality you want to expose to the scripting engine and what functionality you would rather not want mods to meddle with. There are language bindings for lots and lots of scripting languages available for C++. Lua is quite popular for game development, but which one you want to use is eventually a matter of personal taste. You might even consider to create your own scripting language specifically tailored to the needs of your game, but I would advise against this. Developing an own programming language and a good interpreter for it is far more difficult than it seems at first glance. Using an implementation of an existing language which is already tested and documented will save you a lot of work.

# Answer
> 0 votes
One simple way would be to give your modders access to the class definitions, such as the "LivingEntity" you described, that way they can simply derive from the base class, and you dont need to have special handling for modified objects or anything else as their code would be compiled as an object with the right interface for your system.

To then integrate these new objects into your game you would need a way for them to 'register' the new objects if you wanted to use them as part of your base system(for example picking random entities to spawn). A fairly simple way to do this would be to have a central object that deals with holding all the entity types, like the factory method you described but with the option to register new types.

I wont go into detailed descriptions of the systems since you asked a higher level question, so I'll leave it up to you to attempt it if you pick this method then come back with more specific implementation questions

---
Tags: c++, architecture, modding
---


# Question
Title: Is it a good or bad thing to allow hot-loading of changes of game rules without official updates and restarts of server and clients?
I’m working on such feature for my project that we allow the game designer to tweak game rules, from small things like item prices to bigger like probability for different randomizations, while the game is running, and the changes immediately get pushed to server and client in code by just reassigning variable references in code at runtime. There are some doubts in the team from wide range of concerns such that doing so might cause a limbo period of overlapped old and new rules as different variables gets picked up at different concurrent sessions at different phases(such game rules are read-only), and possible interrupted player experiences. Can anyone know or have similar experiences share your insights? Thanks!!

# Answer
> 1 votes
It would be a great idea to have this ability during the development of your game, because it would allow a quite fast testing cycle. When your designers want to toy with the balance of certain variables, they don't need to restart (or even recompile and redeploy) the server after every little change. They can see the change immediately while they are playing the game. Fast test cycles are a **huge** accelerator to the design process. So if you see a feasible way to integrate this into your software architecture without having it bend over backwards, then it might be really worth it in the long run.

How much use you make of this when the game is in production is a different question. Server restarts are annoying for everyone involved, so the more you can do without requiring a restart the better. But the concerns of your team members are valid. You don't want to break stuff due to weird interactions while new rulesets are being applied. This is, however, more of a social problem than a technical problem. **You** need to teach your admins what settings they can tweak while the game is running and what kind of tweaks they should rather do while the server is offline.

In the end, dummying out the ability to do live-changes to those settings where live-changes aren't going to work properly anyway should be trivial.

---
Tags: game-design, architecture
---


# Question
Title: Can I use two Collision Boxes on the same GameObject?
I have two Collision Boxes on the same GameObject. I don't want the Collision Boxes to be triggers. I want the Collision Boxes on the actual GameObject, not its children.

For example, if I want to check for a headshot. My reason for not wanting triggers is that a trigger is already being used. My reason for not wanting children is for cleanliness. I understand there are work arounds. I was wondering if there was a more direct approach.

When there is a collision, how can I check which Collision Box is hit?

# Answer
> 1 votes
If you want to just have one GameObject for your character, you cannot add multiple Colliders of the same type to your GameObject and still have the ability to access all of them in your scripts (only the first in order of components would be accessible). However, you CAN add multiple Colliders of DIFFERENT types while still maintaining accessibility. In your case you could add CapsuleCollider or BoxCollider for the body and a SphereCollider for the head. The script for accessing these Colliders would go as follows:

```
using UnityEngine;
using System.Collections;

public class BulletScript : MonoBehaviour {

CapsuleCollider bodyCollider; //OR BoxCollider bodyCollider;
SphereCollider headCollider;

void Start ()
{
    bodyCollider = desiredGameObject.GetComponent<CapsuleCollider> (); //OR bodyCollider = gameObject.GetComponent<BoxCollider> ();
    headCollider = desiredGameObject.GetComponent<SphereCollider> ();
}

void OnTriggerEnter (Collider other)
{
    if (other == bodyCollider)
    {
        //This happens when the body is hit
    }
    if (other == headCollider)
    {
        //This happens when the head is hit
    }
}

```

This script would be attached to your bullet (make sure to add a Trigger Collider as well). The OnTriggerEnter method would check if any Collider has entered the bullet's Trigger Collider. The if statements check which Collider has entered the Trigger Collider. Problem Solved.

Let me know if you have any questions or suggestions.

# Answer
> 0 votes
I know of a way to do this, if you created your colliders programatically. See the following source code:

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

public class MultipleColliders : MonoBehaviour {

    //Enumeration to tell us what a collider is for
    enum ColliderType
    {
        Head,
        Body
    }

    //A quick lookup for our colliders associated with this gameobject
    Dictionary<Collider2D, ColliderType> Colliders;

    void Start () {
        InitColliders ();
    }

    //Programmatically create our colliders
    void InitColliders()
    {
        Colliders = new Dictionary<Collider2D, ColliderType> ();

        BoxCollider2D boxCollider = transform.gameObject.AddComponent (typeof(BoxCollider2D)) as BoxCollider2D;
        boxCollider.offset = new Vector2 (0, -0.5f);
        boxCollider.size = new Vector3 (0.5f, 1f);
        Colliders.Add (boxCollider, ColliderType.Body);

        CircleCollider2D circleCollider = transform.gameObject.AddComponent (typeof(CircleCollider2D)) as CircleCollider2D;
        circleCollider.offset = new Vector2 (0, 0.5f);
        circleCollider.radius = 0.5f;
        Colliders.Add (circleCollider, ColliderType.Head);
    }

    //Check if our colliders were hit
    void Update () {

        //Raycast mouse cursor when pressed to simulate a hit for our example
        if (Input.GetMouseButtonDown (0)) {

            Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D[] hit = Physics2D.RaycastAll (mousePosition, Vector2.zero);

            //lookup our hits to see what was hit
            for (int i = 0; i < hit.Length; i++)
            {
                if (Colliders.ContainsKey(hit[i].collider)) {
                    Debug.Log ( System.Enum.GetName( typeof(ColliderType), Colliders[hit[i].collider]) + " HIT!");
                }
            }
        }
    }
}

```

So basically, doing it this way, will provide you with the requirements you supplied. It will allow a gameobject to contain multiple colliders without having to be each a child object.

It will also be able to tell you what collider was hit.

Let me know if you have questions about this implementation.

# Answer
> 0 votes
I'd recommend making an empty game object that parents both game objects for the enemy as a whole, and a second one for the head. Then you could write a check based on the bullet intersecting with the head and go from there.

```
using UnityEngine;
using System.Collections;

public Class BulletScript : MonoBehaviour {

public Transform bullet;
//tag as "Bullet"

void Start(){
  bullet = transform;
}

void OnTriggerEnter (Collider other){
   if (other.gameObject.CompareTag("Head"){
     Debug.Log("Headshot.");
   }

   if (other.gameObject.CompareTag("Enemy"){
      Debug.Log("Not a head shot.");
   }
 }
}

```

# Answer
> -1 votes
After some research, I've found an easy way to do this without any workarounds.

When creating Colliders, use different names in each of them, as head, torso, legs, arms. Then on OnCollisionEnter method, you just had to check all of the contact points.

```
void OnCollisionEnter(Collision col)
{
    foreach (ContactPoint contact in col.contacts)
    {
        Debug.Log(contact.thisCollider.name + " hit " + contact.otherCollider.name);

        if (contact.thisCollider.name == "HitBoxHead") {
            Debug.Log("Head Shot");
        }
    }
}

```

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


# Question
Title: Level design / lore writing - how to compel player to go through all locations in a star-shaped level
I am trying to design a map for souls-like game and stumbled upon such problem:

According to the lore i have a self-contained city that is supposed to be built with convenience in mind.

I am currently designing a graph that represents which locations i have within the city and how they are connected to each other.

For the sake of convenience (for people living in the city) it makes sense for this graph to be somewhat reminiscent of a star (a central square/street and other minor streets flowing from it leading to different locations). Thus it would never take too long to go from point A to point B.

The problem is that with such design player has no obvious reason to go through every single location (which i really want to enforce).

The final goal of the game is to reach certain location on the map (not in the city, the city is just a part of a bigger world) and from player's perspective it makes sense to take the shortest path available.

How could i force the player to go through all the locations without making it obvious that the city was designed just for this and not actually for people to live in it?

In some places i would put doors that only open from one side or require keys from a location that player would otherwise not go through, but using this everywhere quickly gets old and annoying. What else can i do?

I'm fine with altering the city's layout as far as it makes sense in the game's world. Like having a city built like a spiral because it's built on a mountain. But then i need to come up with an idea why would people build the city on a mountain in the first place?

Edit: originally i did not make it clear that i to make it unavoidable for the player to go through all locations, not just strongly encourage

# Answer
If you want to make sure the player *must* go through several locations, then each of those locations must have something that is required to progress in some way (abilities, keys, knowledge, etc). If you're looking for a way to *strongly encourage* players to go through several locations, then each of those locations must have some thing the player wants (extra health, money, supplemental knowledge, etc).

This sounds like a Metroidvania style system, where there are new abilities that unlock through the course of the game which unlock new paths to new abilities to let you progress. This is sort of what you said you didn't want, except the keys are not simple McGuffins, but actually useful things for the player to be able to use layer as well.

However, depending on how big a part of the game this city is, you may not want to put a new ability at the end of each street. You may want to rely on a simple McGuffin in most of these cases to be able to get to the last one. For example, you have to bribe, sneak, or fight your way past an NPC who is guarding the exit from town, but the ability to do so can only be earned by performing jobs around the city. Another NPC who lives in the center of town tells you to go fetch a thing from point A and deliver it to point B, then come back for some reward (cash for a bribe, or training for the ability to sneak out fight, etc), and get another job to deliver from point C to point D to get more rewards. Rinse and repeat.

If you're not keen on using NPCs, this could still be accomplished with other methods of assigning tasks to the player, such as a simple scavenger hunt with a list of parts required to fix some broken "thing" in the way of the gate of of town, where fixing it is the only way to get it to move. It can be made obvious in the game that different pieces are going to be found at the end of each of the different roads (eg. with signage in the game world, or straight up goal markers on a minimap). For an added bonus, that thing you just fixed can be legitimately helpful for you later on (or if could fly away and come back to haunt you later as another plot point).

This sounds *sort of* like your problem with requiring just a bunch of keys to get past a bunch of locked doors, but this has the advantage of being nonlinear throughout the town. The player can choose to perform the tasks in any order. Maybe there are other useful items along each path which can help the player later on with other paths. If they're having trouble with one path, they can choose to keep trying or to go down another path first to get extra health, or ammo, or information about a weakness in the armor, etc. depending on your style of game.
> 4 votes

---
Tags: maps, level-design, world-design
---


# Question
Title: Change layout of Unity's Project->Assets pane contents to show longer filenames?
I'm working on a project with assets that have really long filenames. I know about the slider in the lower-right corner of the Project-\>Assets pane, but THAT slider makes the icons absolutely HUGE & only allows the display of filenames that are slightly longer than the default.

Is there a way to either:

* Get Unity to use a view akin to Windows Explorer's "List" view (small icon on the left, long filename on the right)
* Get Unity to truncate long filenames in the **middle**? For example...

+ Full name: `ExtraordinarilyLongFilename-27a.material`
    + How it displays now: `ExtraordinarilyLongF...`
    + How I'd *like* it to truncate: `ExtraordinarilyL...e-27a`

(the general assumption of a middle-truncated long name being that the last few characters are usually the ones that distinguish between multiple files that all begin with the same prefixes)

# Answer
You can either change to a Explorer-style layout, or a single-column layout, both of which will allow you to see the full filename.

First, locate the size slider in the bottom right:

And drag it all the way to the left to get your explorer-style display:

Or use a single column layout by pressing the Hamburger button in the top right of the window and choose One Column Layout, particularly useful if your Project window is oriented more vertically:
> 3 votes

---
Tags: unity
---


# Question
Title: How do I preserve the image detail when making a texture? Unity
I have made a texture, set its shader to 'legacy shaders/diffuse' and dragged some images I like into the texture. When using the texture the images don't look as detailed as before. How can I overcome this?

As you can see, it is just one colour, there are no dark spots anywhere.

# Answer
> 1 votes
It seems like whoever created that icosphere in their 3d modeling program forgot to properly set up texture coordinates (also called UV coordinates). These are coordinates which get assigned to each corner of each polygon and tell the renderer which parts of the texture belong onto that polygon.

If you would like to do this, then the exact steps depend on the 3d modeling program you are using.

---
Tags: unity
---


# Question
Title: How do I get all the childs of each squad?
```
var squads = GameObject.FindGameObjectsWithTag("Squad");
        for(int i = 0; i < squads.Length; i++)
        {
            foreach(Transform squadMember in squads[i])
            {
                squadMembers.Add
            }
        }

```

squadMembers is List

# Answer
Solution I had to add a transform in the foreach loop:

```
squads[i].transform

```

The code:

```
private List<Transform> squadMembers = new List<Transform>();

  Start()
  {
    var squads = GameObject.FindGameObjectsWithTag("Squad");
            for(int i = 0; i < squads.Length; i++)
            {
                foreach(Transform squadMember in squads[i].transform)
                {
                    squadMembers.Add(squadMember);
                }
            }
  }

```
> 0 votes

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


title: Shortest path to a road

text:
# Question
Title: Shortest path to a road
I have a road network and a vehicle that is current off the roads. I want to find the shortest path to any road. An obvious solution is to run a pathfinding algorithm between the current vehicle location and all the points on the road, but that's hardly scalable.

I am curious to know if there is an algorithm out there that I could use to maximize the performance of this operation.

# Answer
When you don't need to arrive at a specific destination, or don't have enough guidance to estimate your distance to a destination with an admissable heuristic for A\*, you can use Dijkstra's algorithm. (Effectively, A\* with no heuristic)

This will enumerate shortest paths from your start position. As you explore each node in order of path distance, you check whether it's a goal (ie. whether it is a road, any road). If it is, you have found the shortest path to a road.
> 2 votes

---
Tags: path-finding
---


title: Drag Object to Collide Unity

text:
# Question
Title: Drag Object to Collide Unity
Please help, I am developing a 2D game for a school project and I want to drag the apple to the think box then when it collides, the apple will go back to the original position then it will add 1 point to the score. I'm just new to Unity. So please help

# Answer
> 1 votes
Alright, so as I'm relatively new to unity and coding myself, I don't know about drag & dropping objects, but I'm sure a quick Google search would help you out with this.

However, regarding the second part: I'll be referring to the three objects as 1, 2 and 3 and to the think boxes as a, b and c.

So you want that once 1 collides with a, 2 collides with b, etc, the score counter will go up by one, then the object will go back to its place.

First, make three new tags each with a different name for example apple, worm and pill and set them to the think box game object. This will be used to recognize which object we collided with.

Now add 2D collider components to both (all three) dragable objects and think boxes, make sure you set them to the correct size and everything, and tick "Is Trigger" on so it only detects collisions but doesn't actually block your object.

Then make a new c# script, this you will add to your dragable apple, worm and pill.

Let's make a few new variables.

```
public float startX
public float startY

public string collisionTag

```

Delete the void start and void update methods as we won't be needing them and instead add:

```
void OnTriggerEnter2D(Collider2D other){
        if (other.gameObject.CompareTag(collisionTag)){
                score++;
                transform.position = new Vector2(startX, startY);
        }
}

```

This method runs when there's a collision from a trigger, then calls this trigger other. What this does is check if the tag of the collided object is equal to the string variable collisionTag which you set in the hierarchy, and if it does, it adds one to score and puts the game object back in its starting location, x and y values you also set in the hierarchy.

We do it this way so you only have to write one script and then set the values manually, which makes it much faster and saves memory.

Now drag the script to each dragable object separately, put the desired x and y values that they'll move to when you want them to move back, and write the exact, case sensitive tag name in the collision tag box and tada! Good luck with your game.

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


title: Pong tutorial / Unity Logic question

text:
# Question
Title: Pong tutorial / Unity Logic question
I've been following this Pong tutorial, which is great: https://noobtuts.com/unity/2d-pong-game. The C#, unity components etc I understand. But what I am having trouble with is understanding the logic of how it reverses the direction of the ball depending on where it hits.

I know that what it is doing is condensing a new Y value to -1, 0, 1, via the hitFactor function, which returns that value and then sets that to the new Y (so going up or down) based on the relative ball position to the paddle, divided by the height/size of the paddle. But that's the bit I don't really truly understand, how does that work and why? I have been using Debug.log to send all the different parts of it to try and understand, as well as visually looking in Unity and trying to figure it out from there via the inspector, but I'm just having a mental block. To me I can vaguely see how this code is finding a relative position and then dividing by the height of the paddle to somehow condense it to this range but I'm really just stuck on it in my head.(the hitfactor function itself is basically where I am stuck)

Here's the function:

```
float hitFactor(Vector2 ballPos, Vector2 racketPos,
            float racketHeight) {
// ascii art:
// ||  1 <- at the top of the racket
// ||
// ||  0 <- at the middle of the racket
// ||
// || -1 <- at the bottom of the racket
return (ballPos.y - racketPos.y) / racketHeight;
}

```

And in context with the collision:

```
if (col.gameObject.name == "RacketLeft") {
    // Calculate hit Factor
    float y = hitFactor(transform.position,
                        col.transform.position,
                        col.collider.bounds.size.y);

    // Calculate direction, make length=1 via .normalized
    Vector2 dir = new Vector2(1, y).normalized;

    // Set Velocity with dir * speed
    GetComponent<Rigidbody2D>().velocity = dir * speed;

```

I'm sure this is a very basic thing, but I am struggling with this type of thing. I am on Khan academy, starting from very basic stuff and working my way up, so no doubt maybe when I get to vectors I might understand this more, but I'd like to try and really get my head around this particular issue.

Sorry for the very basic question, I have been dabbling in C# and Unity for a while, but I have realised my weakness is really in the basic core logic of some things....I am a composer by day but I really enjoy trying to get back into this side of my brain, I guess it's super dusty in there hahaha.

Thanks so much in advance for any help, I truly appreciate it.

# Answer
The `(ballPos.y - racketPos.y) / racketHeight` calculation is what we call a linear interpolation.

`(ballPos.y - racketPos.y)` calculates the distance of ball from the center of the racket.

Then you divide it by the height of the racket to normalize the scale so that if the ball hit the top of the racket the value is 0.5, and if the ball hit the bottom of the racket the value becomes -0.5.

In other words, we scale the range to \[-0.5, +0.5\].

**Note:** This calculation doesn't assure that the value stays within \[-0.5, +0.5\] range. For example, if the ball is above the racket the result will be greater than +0.5, and if it is below the racket the result will be lower than -0.5.

What assures the value to stay within this range is your collision check. If the ball is colliding with the racket, surely it must be touching the racket, therefore it cannot be above or below the racket.

---

Vectors are denoted with tuples. The notation of (8, 3) means 8 on X axis and 3 on Y axis.

(1, 0) is a vector from left to right.

If you increase the Y value it starts pointing upwards. (1, 0.5) points in approx. +26.5 degrees (starting from +x axis).

If you decrease the Y value, it starts pointing downwards. (1, -0.5) points in approx. -26.5 degrees (starting from +x axis).

(0, 1) is a vector from bottom to top.

---

Since your code maps the Y hit point in (-0.5, +0.5) range, we can put that directly in the Y component of the final vector to get a range that starts from (+1, -0.5) and goes to (+1, +0.5).

As you may remember, (+1, -0.5) is a vector that points towards -26.5 degrees and (+1, +0.5) points towards +26.5 degrees. Therefore we created a range of angles of \[-26.5, +26.5\].

---

One final problem is that the length of the vector (1, 0) is not same as the length of the vector, for example, (1, -0.5) or (1, 0.234).

To fix this, we simply normalize the vector, meaning we scale it so that the length of vector equals 1. In Unity, you can simply call `the_vector.normalized` to get the normalized version of the vector.
> 0 votes

# Answer
It just sets the y based on the position of the ball relative to the paddle. At the top it will bounce in a 45 degree angle, at the bottom in a -45 degree angle. It's called linear interpolation.
> 0 votes

---
Tags: unity, pong
---


# Question
Title: How can the fluid stream be stuck to the top of flask?
I created a flask and added a fluid stream to the top of the flask. When I translate the flask, the fluid stream goes along with the top of the flask. How do I achieve this when rotation occurs.

```
   void Start () {
    aa.transform.position = new Vector3(bb.transform.position.x,
    bb.transform.position.y + 4, bb.transform.position.z);
    aa.SetActive(false);
    aa.SetActive(true);
   }

void Update () {
    aa.transform.position = new Vector3(bb.transform.position.x, bb.transform.position.y+4, bb.transform.position.z);
   //aa is the fluid stream and bb is the flask
    cc.transform.position = new Vector3(bb.transform.position.x, bb.transform.position.y + 4, bb.transform.position.z);
    }

```

The traslation works. But you can see the gap between top of flask and rotation here. How do I close that gap?

# Answer
```
// The flask we want to attach to.
public Transform flask;

// The stream object (assuming the liquid flows from its local origin)
public Transform stream;

// Position of the spout in the flask's local space.
public Vector3 spout;

// By running in LateUpdate, we ensure the flask has had a chance to move
// already this frame, before we try to follow it.
void LateUpdate() {
    // Set our stream's origin to the position of the spout after applying
    // the flask's transformation (including translation, rotation, and scale).
    stream.transform.position = flask.TransformPoint(spout);
}

```
> 1 votes

---
Tags: unity, monodevelop
---


title: Multiple Colour Gradient Lerp

text:
# Question
Title: Multiple Colour Gradient Lerp
I want to return a colour for a position t, given an arbitrary number of colour stops - a stop is comprised of a position, and a colour.

Like selecting a colour from a multiple-colour gradient, linearly interpolated between stops.

Positions and point t are floating point numbers and can be negative. Positions and their respective colours are ordered lowest to highest in the arrays.

I would like to avoid conditional statements, as this is for use within a shader.

Code would ideally be in the form:

```
float3 MultiColorLerp(float positions[], float3[] colors, float t) {
    // Returns the color at the point t.
}

```

# Answer
> 0 votes
Since we don't know the size of the arrays here, we need to pass that as a parameter, and we'll need at least a little conditional branching to control the loop.

We can technically avoid other `if`-type branching using ther `step` function to mask-to-zero any colours from segments of the gradient that `t` isn't in, but I don't recommend it. This does all the work of rendering a pixel from every span of the gradient instead of just the span we're in. You might well find that a little branching to find the right span and compute just that one colour is more efficient.

```
float3 MultiColorLerp(float positions[], float3[] colors, float t, int numStops) {
    // If t is less than all stops, use the first color.
    float3 color = colors[0] * step(t, positions[0]);

    // If t is greater than all stops, use the last color.
    color += colors[numStops - 1] * step(positions[numStops - 1], t);

    // Compute blended color for each span, and mask out all but the span containing t
    int start;
    float inRange;
    float s;
    for(int end = 1; end < numStops; end++) {
        start = end - 1;
        inRange = step(positions[start], t) * step(t, positions[end]);
        s = (t - positions[start])/(positions[end]- positions[start]);

        color += inRange * lerp(colors[start], colors[end], s);
    }
}

```

Compare this to a version where we're more accepting of branches:

```
float3 MultiColorLerp(float positions[], float3[] colors, float t, int numStops) {
    // Handle t outside the gradient's range.
    if(t <= positions[0])
        return colors[0];

    if(t >= positions[numStops - 1])
        return colors[numStops - 1])

    // Find the span t sits within.
    int end = 1;
    while(positions[end] < t)
        end++;

    // Blend colors for this span.
    float s = (t - positions[end - 1])/(positions[end] - positions[end - 1]);

    return lerp(colors[end - 1], colors[end], s);
}

```

Since these branches will be reasonably coherent (within any one span of the gradient, all adjacent fragments will take the same path — it's only where the gradient crosses one of its position keys that you'll have neighbours branching inconsistently), I'd be willing to bet a strategy like this one would actually perform better, especially if your gradients have many stops.

---
Tags: unity, shaders, lerp
---


# Question
Title: How can I express Logarithmic and Arithmetic spirals as segmented cubic bezier curves?
I am creating cubic bezier curves using this code from another question I asked. I would like to know how I can express Logarithmic and Arithmetic spirals as segmented cubic bezier curves.

# Answer
> 2 votes
Here I'll use a utility function to produce points on an Archimedean spiral at a particular angle, along with the derivative of the function at that point. To reduce the number of parameters, I'll use the `Transform` of our object to apply translation/scaling/rotation of the curve. You can also use a matrix or add these parameters as additional arguments.

```
Vector3 ArchimedeanSpiral(float spacing, float angle, out Vector3 derivative) {
    float radians = angle * Mathf.Deg2Rad;
    Vector3 direction = new Vector3(Mathf.Cos(radians), Mathf.Sin(radians), 0);
    Vector3 perpendicular = new Vector3(-direction.y, direction.x, 0);

    float b = spacing/360f;

    derivative = transform.TransformVector(b * (direction + radians * perpendicular));
    return transform.TransformPoint(b * angle * direction);
}

```

Now we can choose points on a Bezier spline approximating this spiral like so...

```
Vector3[] ArchimedeanSpiralBezier(float spacing, float startAngle, float endAngle) {
    // Chop the spiral into segments, roughly this many degrees apiece.
    float interval = 90f;
    float angleSpan = endAngle - startAngle;
    int segmentCount = Mathf.Max(Mathf.RoundToInt(Mathf.Abs(angleSpan / interval)), 2);
    Vector3[] bezierPoints = new Vector3[segmentCount * 3 + 1];
    float step = angleSpan / segmentCount;

    // 1.05f is a fudge factor determined empirically,
    // to "puff out" the curve so it doesn't cut the corner too shallowly.
    float derivativeScale = step * 1.05f/3f;
    // The division by 3 is because in an nth order Bezier curve,
    // the velocity at an anchor point is n times the vector to the next point.

    // Initialize the first anchor point on the spline.
    Vector3 derivative;
    bezierPoints[0] = ArchimedeanSpiral(spacing, startAngle, out derivative);
    derivative *= derivativeScale;

    for(int i = 1; i <= segmentCount; i++) {
        int end = i * 3;

        // The next control point is the previous anchor plus the velocity.
        bezierPoints[end - 2] = bezierPoints[end - 3] + derivative;

        // Place the next anchor point.
        float angle = startAngle + i * step;
        bezierPoints[end] = ArchimedeanSpiral(spacing, angle, out derivative);
        derivative *= derivativeScale;

        // Backtrack from this anchor point by the velocity to place its control point.
        bezierPoints[end - 1] = bezierPoints[end] - derivative;
    }

    return bezierPoints;
}

```

For a logarithmic spiral, the same principles apply, just with a different utility function:

```
Vector3 LogarithmicSpiral(float spacing, float angle, out Vector3 derivative) {
    float radians = angle * Mathf.Deg2Rad;
    Vector3 direction = new Vector3(Mathf.Cos(radians), Mathf.Sin(radians), 0);
    Vector3 perpendicular = new Vector3(-direction.y, direction.x, 0);

    float b = spacing/360f;
    float radius = Mathf.Exp(b * angle);

    derivative = transform.TransformVector(radius * (b * direction + Mathf.Deg2Rad * perpendicular));
    return transform.TransformPoint(radius * direction);
}

```

---
Tags: unity, mathematics, geometry
---


# Question
Title: Unity: How many Raycasts per Sphere Collider?
I understand that a simple sphere collider in Unity is a raycast in all directions with a certain length. How many Raycast events does a sphere collider trigger? At what degree increments are the rays cast?

# Answer
Not always a raycast. Unity3D's collision is based on PhysX and it support multiple types of geometry queries:

* **raycasts** test a ray against a geometry object.
* **sweeps** move one geometry object along a line to find the first point of intersection with another geometry object.
* **overlaps** determine whether two geometry objects intersect.

How unity technologies implements every one of them is not exposed as far as i know.

in-depth doc on PhysX
> 2 votes

---
Tags: unity, raycasting, collider
---


title: Terrain collision with sphere and OBB

text:
# Question
Title: Terrain collision with sphere and OBB
I'm implementing my physics engine for my 3D game. So far I've been able to implement collision detection between OBB, spheres and planes. The engine generate contacts and resolve them with an iterative impulse-based approach.

The result is this (so far).

Now I need to detect and generate contacts between a height map terrain and those bounding volumes (sphere and OBB). The terrain looks like this:

I don't know how to do it. I need to detect collisions and generate contact data (contact point, contact normal and interpenetration to feed my existing engine). I know I can't use a SAT because the terrain in not convex. What about ad hoc code for boxes and spheres? or is there a general approach?

**EDIT**

I narrowed down my problem to detecting (and resolving) collisions between a simple convex collidable (sphere/OBB) and triangles (always convex). Since the terrain is stored as an height map I can easily select a subset of triangles to run the algorithm against. I can use the SAT to detect interpenetrations. But what about collision response? How can I generate the necessary contact data (collision point and collision normal) to resolve the collision?

# Answer
Terrain is a difficult collision detection example, as it is complex, so you reduce the complexity of the problem. One possible solution, for static terrain meshes:

Make your terrain out of small manageable chunks. Organise each of them into triangles.

When you load your terrain meshes, generate an AABB and triangle set from the the vertex data. The AABB is for your broadphase, and the triangle set is for your narrow phase.

Once a possible collision is detected, you then perform an OBB/triangle, or sphere/triangle collision check. You can use any narrow phase algorithm you wish at that stage.

This is by no means the most optimal solution, but it's one possible workable solution.
> 2 votes

---
Tags: collision-detection, directx11, collision-resolution, physics-engine, bounding-boxes
---