Tank.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. namespace Mirror.Examples.Tanks
  4. {
  5. public class Tank : NetworkBehaviour
  6. {
  7. [Header("Components")]
  8. public NavMeshAgent agent;
  9. public Animator animator;
  10. public TextMesh healthBar;
  11. [Header("Movement")]
  12. public float rotationSpeed = 100;
  13. [Header("Firing")]
  14. public KeyCode shootKey = KeyCode.Space;
  15. public GameObject projectilePrefab;
  16. public Transform projectileMount;
  17. [Header("Stats")]
  18. [SyncVar] public int health = 4;
  19. void Update()
  20. {
  21. // always update health bar.
  22. // (SyncVar hook would only update on clients, not on server)
  23. healthBar.text = new string('-', health);
  24. // movement for local player
  25. if (isLocalPlayer)
  26. {
  27. // rotate
  28. float horizontal = Input.GetAxis("Horizontal");
  29. transform.Rotate(0, horizontal * rotationSpeed * Time.deltaTime, 0);
  30. // move
  31. float vertical = Input.GetAxis("Vertical");
  32. Vector3 forward = transform.TransformDirection(Vector3.forward);
  33. agent.velocity = forward * Mathf.Max(vertical, 0) * agent.speed;
  34. animator.SetBool("Moving", agent.velocity != Vector3.zero);
  35. // shoot
  36. if (Input.GetKeyDown(shootKey))
  37. {
  38. CmdFire();
  39. }
  40. }
  41. }
  42. // this is called on the server
  43. [Command]
  44. void CmdFire()
  45. {
  46. GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, transform.rotation);
  47. NetworkServer.Spawn(projectile);
  48. RpcOnFire();
  49. }
  50. // this is called on the tank that fired for all observers
  51. [ClientRpc]
  52. void RpcOnFire()
  53. {
  54. animator.SetTrigger("Shoot");
  55. }
  56. [ServerCallback]
  57. void OnTriggerEnter(Collider other)
  58. {
  59. if (other.GetComponent<Projectile>() != null)
  60. {
  61. --health;
  62. if (health == 0)
  63. NetworkServer.Destroy(gameObject);
  64. }
  65. }
  66. }
  67. }