ShootingTankBehaviour.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using UnityEngine;
  2. namespace Mirror.Examples.Additive
  3. {
  4. // This script demonstrates the NetworkAnimator and how to leverage
  5. // the built-in observers system to track players.
  6. // Note that all ProximityCheckers should be restricted to the Player layer.
  7. public class ShootingTankBehaviour : NetworkBehaviour
  8. {
  9. [SyncVar]
  10. public Quaternion rotation;
  11. NetworkAnimator networkAnimator;
  12. [ServerCallback]
  13. void Start()
  14. {
  15. networkAnimator = GetComponent<NetworkAnimator>();
  16. }
  17. [Range(0, 1)]
  18. public float turnSpeed = 0.1f;
  19. void Update()
  20. {
  21. if (isServer && netIdentity.observers.Count > 0)
  22. ShootNearestPlayer();
  23. if (isClient)
  24. transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed);
  25. }
  26. [Server]
  27. void ShootNearestPlayer()
  28. {
  29. GameObject target = null;
  30. float distance = 100f;
  31. foreach (NetworkConnection networkConnection in netIdentity.observers.Values)
  32. {
  33. GameObject tempTarget = networkConnection.identity.gameObject;
  34. float tempDistance = Vector3.Distance(tempTarget.transform.position, transform.position);
  35. if (target == null || distance > tempDistance)
  36. {
  37. target = tempTarget;
  38. distance = tempDistance;
  39. }
  40. }
  41. if (target != null)
  42. {
  43. transform.LookAt(target.transform.position + Vector3.down);
  44. rotation = transform.rotation;
  45. networkAnimator.SetTrigger("Fire");
  46. }
  47. }
  48. }
  49. }