Tank.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. [Header("Movement")]
  11. public float rotationSpeed = 100;
  12. [Header("Firing")]
  13. public KeyCode shootKey = KeyCode.Space;
  14. public GameObject projectilePrefab;
  15. public Transform projectileMount;
  16. void Update()
  17. {
  18. // movement for local player
  19. if (!isLocalPlayer) return;
  20. // rotate
  21. float horizontal = Input.GetAxis("Horizontal");
  22. transform.Rotate(0, horizontal * rotationSpeed * Time.deltaTime, 0);
  23. // move
  24. float vertical = Input.GetAxis("Vertical");
  25. Vector3 forward = transform.TransformDirection(Vector3.forward);
  26. agent.velocity = forward * Mathf.Max(vertical, 0) * agent.speed;
  27. animator.SetBool("Moving", agent.velocity != Vector3.zero);
  28. // shoot
  29. if (Input.GetKeyDown(shootKey))
  30. {
  31. CmdFire();
  32. }
  33. }
  34. // this is called on the server
  35. [Command]
  36. void CmdFire()
  37. {
  38. GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, transform.rotation);
  39. NetworkServer.Spawn(projectile);
  40. RpcOnFire();
  41. }
  42. // this is called on the tank that fired for all observers
  43. [ClientRpc]
  44. void RpcOnFire()
  45. {
  46. animator.SetTrigger("Shoot");
  47. }
  48. }
  49. }