Tank.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // movement for local player
  26. if (isLocalPlayer)
  27. {
  28. // rotate
  29. float horizontal = Input.GetAxis("Horizontal");
  30. transform.Rotate(0, horizontal * rotationSpeed * Time.deltaTime, 0);
  31. // move
  32. float vertical = Input.GetAxis("Vertical");
  33. Vector3 forward = transform.TransformDirection(Vector3.forward);
  34. agent.velocity = forward * Mathf.Max(vertical, 0) * agent.speed;
  35. animator.SetBool("Moving", agent.velocity != Vector3.zero);
  36. // shoot
  37. if (Input.GetKeyDown(shootKey))
  38. {
  39. CmdFire();
  40. }
  41. RotateTurret();
  42. }
  43. }
  44. // this is called on the server
  45. [Command]
  46. void CmdFire()
  47. {
  48. GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, projectileMount.rotation);
  49. NetworkServer.Spawn(projectile);
  50. RpcOnFire();
  51. }
  52. // this is called on the tank that fired for all observers
  53. [ClientRpc]
  54. void RpcOnFire()
  55. {
  56. animator.SetTrigger("Shoot");
  57. }
  58. [ServerCallback]
  59. void OnTriggerEnter(Collider other)
  60. {
  61. if (other.GetComponent<Projectile>() != null)
  62. {
  63. --health;
  64. if (health == 0)
  65. NetworkServer.Destroy(gameObject);
  66. }
  67. }
  68. void RotateTurret()
  69. {
  70. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  71. RaycastHit hit;
  72. if (Physics.Raycast(ray, out hit, 100))
  73. {
  74. Debug.DrawLine(ray.origin, hit.point);
  75. Vector3 lookRotation = new Vector3(hit.point.x, turret.transform.position.y, hit.point.z);
  76. turret.transform.LookAt(lookRotation);
  77. }
  78. }
  79. }
  80. }