Tank.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. public Transform turret;
  12. [Header("Movement")]
  13. public float rotationSpeed = 100;
  14. [Header("Firing")]
  15. public KeyCode shootKey = KeyCode.Space;
  16. public GameObject projectilePrefab;
  17. public Transform projectileMount;
  18. [Header("Stats")]
  19. [SyncVar] public int health = 4;
  20. void Update()
  21. {
  22. // always update health bar.
  23. // (SyncVar hook would only update on clients, not on server)
  24. healthBar.text = new string('-', health);
  25. // take input from focused window only
  26. if(!Application.isFocused) return;
  27. // movement for local player
  28. if (isLocalPlayer)
  29. {
  30. // rotate
  31. float horizontal = Input.GetAxis("Horizontal");
  32. transform.Rotate(0, horizontal * rotationSpeed * Time.deltaTime, 0);
  33. // move
  34. float vertical = Input.GetAxis("Vertical");
  35. Vector3 forward = transform.TransformDirection(Vector3.forward);
  36. agent.velocity = forward * Mathf.Max(vertical, 0) * agent.speed;
  37. animator.SetBool("Moving", agent.velocity != Vector3.zero);
  38. // shoot
  39. if (Input.GetKeyDown(shootKey))
  40. {
  41. CmdFire();
  42. }
  43. RotateTurret();
  44. }
  45. }
  46. // this is called on the server
  47. [Command]
  48. void CmdFire()
  49. {
  50. GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, projectileMount.rotation);
  51. NetworkServer.Spawn(projectile);
  52. RpcOnFire();
  53. }
  54. // this is called on the tank that fired for all observers
  55. [ClientRpc]
  56. void RpcOnFire()
  57. {
  58. animator.SetTrigger("Shoot");
  59. }
  60. [ServerCallback]
  61. void OnTriggerEnter(Collider other)
  62. {
  63. if (other.GetComponent<Projectile>() != null)
  64. {
  65. --health;
  66. if (health == 0)
  67. NetworkServer.Destroy(gameObject);
  68. }
  69. }
  70. void RotateTurret()
  71. {
  72. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  73. if (Physics.Raycast(ray, out RaycastHit hit, 100))
  74. {
  75. Debug.DrawLine(ray.origin, hit.point);
  76. Vector3 lookRotation = new Vector3(hit.point.x, turret.transform.position.y, hit.point.z);
  77. turret.transform.LookAt(lookRotation);
  78. }
  79. }
  80. }
  81. }