Search Unity

Tanks!!! Reference Project, for Unity Multiplayer Q&A

Discussion in 'Community Learning & Teaching' started by richard-lee, Feb 17, 2017.

  1. richard-lee

    richard-lee

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    50


    Built on Unity's tutorials, Tanks!!! goes further, turning them into a live, fully featured, Multiplayer game. Get the game now, on iOS, Android, MacOS, or Windows. Then, get the source, available from the Asset Store!





    Tanks!!! Reference Project is a Unity Multiplayer project that is available for free on the Asset Store. If you’ve gone through the Multiplayer tutorials on our site, it should look familiar. It’s based on the existing Tanks! tutorials, but amped up into a fully featured game. This project includes code, assets, reference material… everything you need to build the full game.

    We made this project because we’ve seen and gotten a lot of direct feedback regarding how one implements Multiplayer in a production environment. So, it demonstrates how to solve some common Multiplayer challenges like compensating for latency and cheating.

    Because this is architected as a production-ready game, it may be harder to digest than the existing Tanks! tutorials. So to ease people in, this project comes with a complete reference guide. You can also watch 3 part video walkthrough on Youtube right now.
    So, try out the game and then download it from the Asset Store. Then, let us know what you think on this thread. I’m especially curious if this game really does help people understand Unity Multiplayer better and if we at Unity should create more “reference projects” like this one. PM me if you have detailed feedback.

    If you run into any technical issues or questions, reply to this thread. Alec (AlecLarsen1989) was lead getting this project shipped and will also answer questions directly.
     
    Reshad, Troast, eses and 5 others like this.
  2. DungDajHjep

    DungDajHjep

    Joined:
    Mar 25, 2015
    Posts:
    202
    stuck here when use android phone to join my unity editor host
     

    Attached Files:

    Softgraph likes this.
  3. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Can you send through more details? For example, did you deploy your own instance of the game to your Android device? The Live versions (on Google Play/App Store) are not compatible with the version from the asset store.

    If you did deploy your own version to your Android device then are you using Unity 5.5.1? If you are, could you possibly send through the adb logcat dump from your Android device, as this would allow us to pinpoint the problem. If you need any further assistance, feel free to reach out :)
     
    Last edited: Feb 28, 2017
  4. Gymhgy123

    Gymhgy123

    Joined:
    Jan 15, 2017
    Posts:
    4
    Where's the difference between the Tanks! multiplayer project? Don't they both allow multiplayer, except this one is more cartoony?
     
  5. richard-lee

    richard-lee

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    50
    This one uses the Multiplayer services (Relay, Matchmaker). It's also architected as a production game, which is important for multiplayer where you have network-specific considerations to workaround e.g. cheating, compensating for latency.
     
  6. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    Thanks for bringing us this nice demo project! :)

    I've noticed, that all models have two versions of the same mesh, one is used as the default visible mesh, and the other has smoothed normals and is used to draw the outline and cast shadows. Is there any specific reason for this setup? I thought about writing custom smooth normal data into a separate uv channel on model import and then let my shader use that channel to get custom normals only for the outline part, so I wouldn't have to import double the amount of meshes. Does this lead to multiple shader passes or somehow break batching or why would I want to manually import separate models?
     
  7. IronmanXXX

    IronmanXXX

    Joined:
    Aug 7, 2013
    Posts:
    11
    Just started playing around with Tanks!!!

    I'm getting 126 errors.

    for example:
    'TankHealth' does not contain a definition for ''TANK_SUICIDE_INDEX"

    I went poking around TankHealth.ca

    I am seeing a bunch of place holder functions.
    For example:
    public void TakeDamage(float amount)
    {
    // Adjust the tank's current health, update the UI based on the new health and check whether or not the tank is dead.
    }


    Is this expected?
    I did a reimport and got the same results.
    I have watched the 3 videos and read the TanksReference.pdf

    Is there somewhere that goes into what should be coded for these functions?
     
  8. IronmanXXX

    IronmanXXX

    Joined:
    Aug 7, 2013
    Posts:
    11
    I believe my issue was I imported over the old Tanks tutorial files and some old files got left behind.
    I do not see _Complete-Game.unity, _Complete-Game.meta, _Completed-Assets.meta like the original Tanks did.

    Building and running works.
     
    AdmiralThrawn likes this.
  9. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Glad you managed to get it sorted. If you have any more questions, feel free to ask :)
     
  10. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    That's a great question!

    The reason it's a different mesh is a fairly simple optimisation. While I don't anticipate any hiccups with your proposed approach, it would defeat the true main purposes of smoothing out the normals in the first place:

    The mesh with smooth normals and no UVs means that Unity can represent that mesh without needing to split verts at UV islands or hard normal edges, so the same geometry ends up with fewer verts sent to the GPU. This means we could render the shadows and outlines with fewer overall verts, though with a slight extra memory cost.

    It also opened up the possibility to literally eliminate verts that would not contribute to the shape of the shadow or outline (although in practice we found we didn't really need to do this all that much, if it all). You can generally get away with using a significantly lower-resolution mesh for a shadow without any visible artifacts. It's also useful to do this so that you can make thin things that cause shimmery shadows thicker in the shadow mesh, to help eliminate those graphical artifacts.

    The other, more pragmatic reason for smoothing the normals is for the outline portion of the effect (although there is no reason the outline mesh and shadow meshes need to be the same, it just made sense to do it in this case). It's a fairly naive outline approach that simply pushes verts outwards along their normals, and if there's a vert cut for hard shading, the faces will split apart and there will be gaps in the outline. While your approach will still work for this, there is a (probably minuscule) chance that the split verts, even though they have the same normal, may cause seams to appear in your outline. Chances are that won't happen on desktop platforms, but mobile GPUs tend to use less accurate approximations and position representations in their hardware, and it's possible, though perhaps not likely, that it could happen there. That's almost certainly not a big concern though.

    So in summary, the primary reason to not do it your way really is just because it'd result in a higher total vert count in the scene. If that's not a concern of yours, then there's no especially compelling reason not to do it that way.
     
    Xarbrough and Luke-Lamothe like this.
  11. Alexbeav

    Alexbeav

    Joined:
    Jan 15, 2017
    Posts:
    15
    This is brilliantly, mind-blowingly, amazing! Not only it's cross platform but also CROSS PLAY? I'm going to test playing against my brother on the PC while I'm on my Android phone, I have to see it to believe this!
     
  12. Gordinho

    Gordinho

    Joined:
    Feb 10, 2013
    Posts:
    10
    Hi,
    I have some questions about this template. If I go to the prefabs folder and go to the tanks folder, I drag one of the tanks to a scene but it seems that its not complete, it doesn't have movement. Shouldn't a prefab be the final thing?.
    Another question, why do people make a level, put the art work and enemies on scene and them make the player appear by code?. Whats the point?. It only makes people confused. Why not put everything on scene and make things easier to change, to custom.
    Thanks.
     
  13. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Awesome. Hope you enjoy it!!!
     
  14. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Some good questions.

    Prefabs are used as template objects that store common functionality. So in our case, we have three different types of tanks. These tanks share common functionality, e.g. shooting and driving. So this common functionality was placed on a prefab (CompleteTank) so that if we need to change/add to it then we do it in one place. The different tanks have different visuals so these were all stored in separate prefabs, which are then parented to the CompleteTank prefab in code.

    This brings us to the 2nd question. For this game, the player needs to be instantiated in code because it is a network game - there is no way of knowing how many players are going to be playing the game when building the scene. The second reason for instantiating the players in code is the fact that there are three different tanks (and different decorations and colors). There is no way of knowing what tank the player will use when building the scene.
     
    ibyte likes this.
  15. Gordinho

    Gordinho

    Joined:
    Feb 10, 2013
    Posts:
    10
    Thank you.
     
  16. Gordinho

    Gordinho

    Joined:
    Feb 10, 2013
    Posts:
    10
    Hi again,
    Sorry to trouble you again. After reading "complete tank prefab" I went to check the template and for my disappointment I couldn't find it. I came back to this post and then I read "complete tank prefab in code"
    Could I ask a big favor to Unity?. Could you put on this template or the other tanks template, a prefab of the complete tank with this sort of firing system?. I really like it and I would like to mod it and try to learn how you do it.
    If you can't put the prefab on the template, could you export as a package and make available a link in this forum?.
    Thank you again for your support and paciente.
     
  17. Acid-NN-9

    Acid-NN-9

    Joined:
    Apr 29, 2015
    Posts:
    10
    AlecLarsen1989 likes this.
  18. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi Gordinho

    It's not a simple process of combining two prefabs because the code does set up some dependencies (because of networking and game management) but let me see if I can direct you. The best way to get an understanding of how the game is setup is to run it in editor and inspect the various game elements. Firstly, open the scene called "SplashScreen" and let's hit run. Then start a Training level (let's pick level 1). In the scene hierarchy view there is an instance of CompleteTank, as seen in the image below.
    forum1.png
    If you click on the instance of the CompleteTank and check the inspector, you will notice multiple components - scroll down until you see TankShooting, as per the screen-grab above. You will also notice the TankMovement script. These scripts have handle the control of the tank. If you scroll down further, you will see TankKeyboardInput and TankTouchInput. These scripts pass user input to the TankShooting and TankMovement scripts. The reason for this is that this game is cross platform and this is the best way to ensure code re-use.

    So I've listed some of the code that is essential to the tank control (TankShooting, TankMovement, TankKeyboardInput and TankTouchInput) so feel free to look through/modify those files. Test your changes it in the Training missions. You can also make use of your IDE (MonoDevelop or Visual Studio) and set break points in the abovementioned files and use the Debugger to see how the scripts work.
     
  19. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Thanks for the kind words - we had a great team :)
     
    AdmiralThrawn likes this.
  20. mauri_galvez

    mauri_galvez

    Joined:
    Dec 9, 2016
    Posts:
    4
    I think this project has been a great guide for me to get into creating a complete multiplayer game! At the moment I'm working on an on-rails shooter. I have been having issues when it comes to parenting the player to a network transform. It would be great if someone could give me advice on the topic. Thanks! :)
     
  21. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi Mauri. Please give me more details about what you're struggling with and I will try to point you in the right direction :)
     
  22. orkungo

    orkungo

    Joined:
    May 3, 2014
    Posts:
    62
    Wow congrats, that is a nice state of coding. Could you please provide class diagrams to fully understand the architecture? Since my game is very close to the Tanks!!!, I would like to take the project as reference and further add asset bundles and a player database.
     
    Last edited: May 3, 2017
  23. apatton

    apatton

    Joined:
    Sep 7, 2013
    Posts:
    8
    Hi, I'm seeing a bunch of errors when I play LobbyScene and click "Create Game" or "Customize". Also no UI appears, but if I manually toggle off and on the CreateGame/Customization gameobjects at runtime then the UI shows up.

    All the errors are along the lines of:

    Trying to remove Background (UnityEngine.UI.Image) from rebuild list while we are already inside a rebuild loop. This is not supported.
    UnityEngine.Canvas:SendWillRenderCanvases()
     
  24. richard-lee

    richard-lee

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    50
    Hey the docs are a bit behind but check out the following video. Talk by our network API engineer.
     
  25. orkungo

    orkungo

    Joined:
    May 3, 2014
    Posts:
    62
    Thank you Richard Lee, video is great, giving lots of information that I have been missing. Additionally to the class diagrams Alexei is talking, replay system seems great! Is it available now, I could not find much information about it?

    I would like to ask another practical question about the multiplayer feature from the Tanks!!! perspective. As a best practice to prioritise, would it be better to give a higher priority to the multiplayer feature at the beginning of the development or provide it as a later update after the development of all single player features such as achievements, AI etc. ?
     
    Last edited: May 9, 2017
  26. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi apatton. Sorry to see that you're having issues with the project. Could you please send me more details so that we can help you resolve this? Specifically, I would like to know what version of Unity you are using, as well as your operating system and what target platform you are set to. Thanks so much :)
     
  27. richard-lee

    richard-lee

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    50
    Like a lot of software development, the longer you put it off, the more you tech debt you'll have repay later. Though the tech debt seems to build up faster with networked features. It impacts how you architect code, managers, etc. The majority of customers that I've spoken to would recommend building multiplayer from the start. At the very least ,with multiplayer in mind.
     
  28. orkungo

    orkungo

    Joined:
    May 3, 2014
    Posts:
    62
    Thanks a lot :) I have it in mind also at the architecture, but seems I will re-prioritise the features and give a higher priority to multiplayer.
     
  29. apatton

    apatton

    Joined:
    Sep 7, 2013
    Posts:
    8
    64-bit Windows 10 using Unity 5.6.0f3 (64-bit) with target as PC, Mac & Linux Standalone and <DX11>

    I've recreated the project with just the tanks package, but can't get the issue to go away.

    Edit: Issue appears to be fixed in 5.6.1f1.
     
    Last edited: May 22, 2017
  30. LLRx

    LLRx

    Joined:
    Jul 31, 2014
    Posts:
    3
    I want to change languge of game completely. But there are some problem to find language files. For example I couldn't find the Tanks description data to change tanks descriptions . Also I want to change the Single Player quests descriptions but I couldn't find the datas.
     
  31. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi apatton

    I'm glad to see that this issue was resolved in 5.6.1f1 :). I did try to reproduce this issue on a 64 bit Windows 10 machine using Unity 5.6.0f3 (64 bit) and I could not replicate the problem you described. If you could possibly give me your complete editor log (console output) and exact steps to reproduce the problem then I could investigate it.

    Many thanks :)
     
  32. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi LLRx

    The Tanks!!! project was not designed with localization in mind. That being said, all of the text descriptions can be found with in configuration scriptable objects. These are located in Assets/Prefabs/Configuration. The screen grab below shows the MapList configuration object. The fields are quite self-explanatory - you can change the Name and Description but avoid changing the Scene Name.

    MapList.png
     
  33. LLRx

    LLRx

    Joined:
    Jul 31, 2014
    Posts:
    3
    Thank you for answering but there is just 4 configure file. I couldn't find the other parts. I will show the parts on the pictures which I want to change :


    This is tank description in modification part



    and this is the Single Player quest part. Please help me to find these language datas
     
  34. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi LLRx

    So the Tanks descriptions can be edited by locating the DynamicObjectLibrary prefab and then editing at the TankLibrary component. The objective text is a little more difficult to edit, as the game was not designed with localisation in mind. For this you need to edit scripts. Go through each script file in Scripts/Rules/SinglePlayer/Objectives and change the objectiveSummary and objectiveDescription properties.

    I hope this helps.
     
  35. bspin

    bspin

    Joined:
    Mar 15, 2015
    Posts:
    4
    In one the video's it is mentioned that there is a write up on how to minimize lag etc. However this write up is not linked in the video's or here.. Could you link me to this write up?
     
  36. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi bspin. Thanks for your question :). The write-up on lag compensation using client-side prediction is describe in Section 5 of the Tanks Reference PDF. This can be found at Assets/TanksReference_560F3.pdf.
     
  37. fnaveedshah

    fnaveedshah

    Joined:
    Dec 15, 2013
    Posts:
    6
    IndexOutOfRangeException: tanks index is invalid , i was trying to add new Tank someone help?
     
  38. fnaveedshah

    fnaveedshah

    Joined:
    Dec 15, 2013
    Posts:
    6
    IndexOutOfRangeException: tanks index is invalid , i was trying to add new Tank someone help?
    //Returns whether a tank for a given index is unlocked.
    public bool IsTankUnlocked(int index)
    {
    if (m_Data.unlockedTanks.Length > index && index >= 0)
    {
    return m_Data.unlockedTanks[index];
    }

    return false;
    }

    //Allows a tank index's unlocked status to be set. Defaults to unlocking the tank.
    public void SetTankUnlocked(int index, bool setUnlocked = true)
    {
    if (m_Data.unlockedTanks.Length > index && index >= 0)
    {
    m_Data.unlockedTanks[index] = setUnlocked;
    }
    else
    {
    throw new IndexOutOfRangeException("Tank index invalid");
    }

    SaveData();
    }

    //Returns whether a decoration for a given index is unlocked.
    public bool IsDecorationUnlocked(int index)
    {
    if (m_Data.decorations.Length > index && index >= 0)
    {
    return m_Data.decorations[index].unlocked;
    }

    return false;
    }

    //Allows a decoration index's unlocked status to be set. Defaults to unlocking the decoration.
    public void SetDecorationUnlocked(int index, bool setUnlocked = true)
    {
    if (m_Data.decorations.Length > index && index >= 0)
    {
    m_Data.decorations[index].unlocked = setUnlocked;
    }
    else
    {
    throw new IndexOutOfRangeException("Tank index invalid");
    }

    SaveData();
    }




     
  39. AlecLarsen1989

    AlecLarsen1989

    Joined:
    Feb 7, 2017
    Posts:
    18
    Hi fnaveedshah :) Thanks for the question. What this error means is that the tank does not exist in the TankLibrary. This can be found on the DynamicObjectLibrary under Assets/Prefabs. From the screen shot you can see that I've added a new tank (it's a modified armadillo tank) called the Armadillo MK2. It will look like the Armadillo because of the visual prefab but will play differently because of the stats. Screen Shot 2017-06-23 at 8.33.34 AM.png

    Also remember, that because this is a network game that you should always build both client and server after changes so that the builds are in sync (functionality wise).

    I hope this helps :)
    Alec
     
  40. Muhamad_Faizol

    Muhamad_Faizol

    Joined:
    Jan 21, 2017
    Posts:
    47
    Hi Alec,

    I really appreciate your patience in explaining the details about this big production level Tanks!!! Reference Project to the community. For a newbie like me, I can't thank you enough for your help.

    Since the whole project encompasses so many levels (including advanced networking concept and so forth), I would like to request, if possible, to have a little bit of breakdowns of the code organizations and the data flow within the game. For example, like in your explanation above to fnaveedshah, perhaps a simple diagram would help newbies like me to understand which scripts should we be looking into if we want to modify certain aspects of the newly added tanks, or how to contain the mainmenu in its own unitypackage, for example. By starting from the basic we the newbies then can learn how these parts in the game are interconnected with each other, and ultimately to study the advanced networking features implemented in this game. Surely it doesn't have to be detailed, just enough to be a basic guide for us all to study the architecture of the game,

    Thank you.

    Cheers,
    Faizol
     
    Last edited: Jun 28, 2017
  41. Josh-Tim

    Josh-Tim

    Joined:
    Dec 8, 2016
    Posts:
    4
    Is there any Chance i could get this in 5.5 without going through the back up and upgrade and downgrade process??

    I would like to download the asset but it seems I'm too late... It requires me to upgrade to unity 5.6. I reverted to unity 5.5 when i got my google developers account because i realized the only way i could get the google play services to work is if my unity version is 5.5 and I'm using google play services in my game
     
  42. JakuDev

    JakuDev

    Joined:
    Jun 27, 2017
    Posts:
    1
    How i can add a new tank? Sorry i'm very newest
     
  43. richard-lee

    richard-lee

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    50
    Jadara, I will PM you an older version of the project.
     
  44. bspin

    bspin

    Joined:
    Mar 15, 2015
    Posts:
    4
    Thanks for your response! doing a full read up now :)
     
  45. wtadlock

    wtadlock

    Joined:
    Aug 1, 2016
    Posts:
    15
    Hey Alex or Richard, awesome project from what I can see so far. You mention in a post above about TanksReference_560F3.pdf. I just downloaded this asset into a new project and that file does not exist anywhere in the folder. Can you PM me that file or direct me to a link on the web that has it?

    Thanks,

    Walter
     
  46. fnaveedshah

    fnaveedshah

    Joined:
    Dec 15, 2013
    Posts:
    6
    Ty for Rpl sir
    i added new tanks with the method you mentioned, but my problem is when i tried to purchase that tank in shop , it gives me error . please check screen shot
     

    Attached Files:

    Last edited: Jul 2, 2017
  47. LLRx

    LLRx

    Joined:
    Jul 31, 2014
    Posts:
    3
    I almost finished the translating but there are some part which I couldn't find to change.
    Shooting Range beginning screen

    After destroy the crate screen

    During the lobby room, I want to change the join button text

    inside of the room, I want to change ready button

    During the game in settings , I want to change this volume texts.
    These are my last translating chase. Where can I find the data sources of these screens. Help me please
     
  48. fnaveedshah

    fnaveedshah

    Joined:
    Dec 15, 2013
    Posts:
    6
    i added new tank with the method you mentioned, but problem is when i tried to purchase that tank in shop , it gives me error , can someone help me? tank error.png
     
  49. alexdion

    alexdion

    Joined:
    Jul 11, 2017
    Posts:
    3
    Hi. I'm creating my first multiplayer game based on this one. The game is ready but I'm stuck in a situation where the shots are delayed and I can not fix it. Could someone please help me?
    Following are the TankController_Net and TankSooting_net scripts.
    Tks...


    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.Networking;
    5.  
    6. public class TankShooting_Net : NetworkBehaviour
    7. {
    8.     [SerializeField] float power = 800f; //Quão difícil atirar com as balas de canhão
    9.     [SerializeField] Transform gunBarrel; //Onde as armas disparam
    10.     [SerializeField] public GameObject shell; // Prefab of the shell.
    11.  
    12.     public AudioSource m_ShootingAudio;         // Reference to the audio source used to play the shooting audio. NB: different to the movement audio source.
    13.     public AudioClip m_FireClip;                // Audio that plays when each shot is fired.
    14.  
    15.     //O método Reset() usamos o código lento (Run Slow Code), como "localizar" no
    16.     //Editor onde o impacto no desempenho não afetará os jogadores na execução
    17.     void Reset()
    18.     {
    19.         //Pega a localização do canhão
    20.         gunBarrel = transform.Find("GunBarrel");
    21.     }
    22.  
    23.     void Update()
    24.     {
    25.         //Se não for o Local Player, retorne. Note que não podemos remover este script
    26.         // de non-Local players, assim como fizemos com o Script TankController.
    27.         //A razão para isso é que o script tem um comando (CmdSpawnShell) que precisa
    28.         //existir neste objeto mesmo que ele não seja o Local Player
    29.         if (!isLocalPlayer)
    30.             return;
    31.  
    32.         //Se nós clicarmos no mouse,  tocar na tela ou apertar o spacebar
    33.         if (Input.GetButtonDown("Fire1") || Input.GetButtonDown("Jump"))
    34.         {
    35.             //Roda o comando no servidor para gerar uma arma
    36.             CmdSpawnShell();
    37.         }
    38.     }
    39.  
    40.     //Este comando é chamado do LocalPlayer e executado no servidor. Note que
    41.     // o comando precisa começar com 'Cmd'
    42.     [Command]
    43.     void CmdSpawnShell()
    44.     {
    45.         //Nós instanciamos uma arma no cano da arma com a rotação correta
    46.         GameObject instance = Instantiate(shell, gunBarrel.position,
    47.             gunBarrel.rotation) as GameObject;
    48.         //Localizamos o componente RigidBody da arma e adicionamos uma força direta para ele
    49.         instance.GetComponent<Rigidbody>().AddForce(gunBarrel.forward * power);
    50.  
    51.         //Finalmente, vamos instanciar este objeto na rede para que todos os jogadores visualizem
    52.         NetworkServer.Spawn(instance);
    53.  
    54.         // Change the clip to the firing clip and play it.
    55.         m_ShootingAudio.clip = m_FireClip;
    56.         m_ShootingAudio.Play();
    57.     }
    58. }
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityStandardAssets.CrossPlatformInput;
    4. using UnityEngine.Networking;
    5.  
    6. public class TankController_Net : NetworkBehaviour
    7. {
    8.     public AudioSource movementAudio; //Faz referência ao audio source usado para tocar o som do motor. Nota: Diferente do audio source dos tiros (shooting)
    9.     public AudioClip engineIdling; //Audio para ser tocado quando o tanque não está em movimento
    10.     public AudioClip engineDriving; //Audio para ser tocado quando o tanque está em movimento
    11.     public float pitchRange = 0.2f; //A quantidade pela qual o passo dos ruídos do motor pode variar
    12.  
    13.     private float m_OriginalPitch; //O tom da fonte de áudio no início da cena.
    14.     private float m_MovementInputValue; //O valor atual do movimento de entrada
    15.     private float turnInputValue; //O valor atual da rotação de entrada
    16.  
    17.     [Header("Movimentos Variáveis")]
    18.     [SerializeField]
    19.     float movementSpeed = 10.0f; //A velocidade do tanque
    20.     [SerializeField]
    21.     float turnSpeed = 45.0f; //A velocidade de rotação do tanque
    22.  
    23.     [Header("Variáveis de posição da Câmera")]
    24.     [SerializeField]
    25.     float cameraDistance = 16f; //Distância que a câmera deve ficar do tanque
    26.     [SerializeField]
    27.     float cameraHeight = 16f; //Altura que a câmera deve estar do chão
    28.  
    29.     Rigidbody localRigidBody; //Cache da referência para o RigidBody
    30.     Transform mainCamera; // Referência para cena da Main Camera
    31.     Vector3 cameraOffset; //Um Vector3 que contém informação quão atrás e ao alto a câmera deve manter do tanque
    32.  
    33.     void Start()
    34.     {
    35.         //Se o tank não for o Local Player
    36.         if (!isLocalPlayer)
    37.         {
    38.             //Este tanque não precisa controlar a Camera, nem qualquer outra intereção
    39.             Destroy(this);
    40.             return;
    41.         }
    42.  
    43.         //Pegar a referencia para o objeto RigidBody desde que nós estaremos usando-o
    44.         localRigidBody = GetComponent<Rigidbody>();
    45.  
    46.         //Setar o offset da camera para uso futuro
    47.         cameraOffset = new Vector3(0f, cameraHeight, -cameraDistance);
    48.  
    49.         //Localizar a cena da main Camera e movê-la dentro da posição correta
    50.         mainCamera = Camera.main.transform;
    51.         MoveCamera();
    52.  
    53.         // Store the original pitch of the audio source.
    54.         m_OriginalPitch = movementAudio.pitch;
    55.     }
    56.  
    57.     void FixedUpdate()
    58.     {
    59.         //Pegar o input Vertical e Horizontal. Note que podemos pegar o input de
    60.         //qualquer plataforma usando a classe CrossPlatformInput
    61.         m_MovementInputValue = CrossPlatformInputManager.GetAxis("Vertical");
    62.         turnInputValue = CrossPlatformInputManager.GetAxis("Horizontal");
    63.  
    64.         //Calcular e aplicar a nova posição
    65.         Vector3 deltaTranslation = transform.position +
    66.             transform.forward * movementSpeed * m_MovementInputValue * Time.deltaTime;
    67.         localRigidBody.MovePosition(deltaTranslation);
    68.  
    69.         //Calcular e aplicar a nova rotação
    70.         Quaternion deltaRotation = Quaternion.Euler(
    71.             turnSpeed * new Vector3(0, turnInputValue, 0) * Time.deltaTime);
    72.         localRigidBody.MoveRotation(localRigidBody.rotation * deltaRotation);
    73.  
    74.         //Atualizar a posição da câmera
    75.         MoveCamera();
    76.  
    77.         //Som do motor
    78.         EngineAudio();
    79.     }
    80.  
    81.     //Este método move a câmera para o correto ponto atrás do jogador
    82.     void MoveCamera()
    83.     {
    84.         mainCamera.position = transform.position; //...posição da camera no tanque
    85.         mainCamera.rotation = transform.rotation; //...alinha a camera com o tanque
    86.         mainCamera.Translate(cameraOffset); //move a camera para cima e fora do tanque
    87.         mainCamera.LookAt(transform); //...move a camera sobre o tanque
    88.     }
    89.  
    90.     private void EngineAudio()
    91.     {
    92.         // If there is no input (the tank is stationary)...
    93.         if (Mathf.Abs(m_MovementInputValue) < 0.1f && Mathf.Abs(turnInputValue) < 0.1f)
    94.         {
    95.             // ... and if the audio source is currently playing the driving clip...
    96.             if (movementAudio.clip == engineDriving)
    97.             {
    98.                 // ... change the clip to idling and play it.
    99.                 movementAudio.clip = engineIdling;
    100.                 movementAudio.pitch = Random.Range(m_OriginalPitch - pitchRange, m_OriginalPitch + pitchRange);
    101.                 movementAudio.Play();
    102.             }
    103.         }
    104.         else
    105.         {
    106.             // Otherwise if the tank is moving and if the idling clip is currently playing...
    107.             if (movementAudio.clip == engineIdling)
    108.             {
    109.                 // ... change the clip to driving and play.
    110.                 movementAudio.clip = engineDriving;
    111.                 movementAudio.pitch = Random.Range(m_OriginalPitch - pitchRange, m_OriginalPitch + pitchRange);
    112.                 movementAudio.Play();
    113.             }
    114.         }
    115.     }
    116. }
     
  50. miterrooter

    miterrooter

    Joined:
    Oct 4, 2016
    Posts:
    3
    Firstly thank you for this excellent start into a full feature networking game. I have two questions relating to the project.

    Does this have any methods of lag compensation included like holding previous state or estimating position?

    And the second query Is how would I get this game to work with multiple instance on the one machine(preferably on localhost). I am moving from the unity multiplayer lobby example which is very difficult to expand and am trying to modify this sample as a template for my own menu system.

    At the moment just trying to start a "Created Game" will cause the m_MenuUi.ShowInfoPopup("Failed to create game.", null); line to be executed in the StartMatchmakingGame Method of the CreateGame Class.

    I assume this is due to me not setting up Unity relay servers in the downloaded project. I am trying to add in menu options to get local hosting to work and obviously I have no success yet.

    The TanksReference_560F3.pdf. does not seem to be in my project if a PDF document(or any accompanying document) exists it would be awesome if someone could link me to it.