Advertisement
Munchy2007

Unet5Tut5Pt1PlayerShooting

Feb 24th, 2016
4,621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.Networking;
  4.  
  5. public class PlayerShoot : NetworkBehaviour {
  6.     [SerializeField] float fireRate = 0.5f;
  7.     LineRenderer laser;
  8.     float nextFireTime;
  9.  
  10.     public override void OnStartLocalPlayer ()
  11.     {
  12.         enabled = true;
  13.     }
  14.  
  15.     public override void OnStartClient ()
  16.     {
  17.         laser = transform.Find("Laser").GetComponent<LineRenderer>();
  18.         laser.enabled = false;
  19.         enabled = false;
  20.     }
  21.  
  22.     void Update () {
  23.         if(Input.GetAxis("Fire1") != 0 && canFire)
  24.         {
  25.             nextFireTime = Time.time + fireRate;
  26.             Fire();
  27.         }
  28.     }
  29.  
  30.     void Fire()
  31.     {
  32.         Ray ray = new Ray(laser.transform.position,transform.forward);
  33.         RaycastHit hit;
  34.         if(Physics.Raycast(ray, out hit, 10f))
  35.         {
  36.             var hitPlayer = hit.collider.gameObject;
  37.             CmdDoShotSomeone(gameObject, hitPlayer);
  38.         }
  39.  
  40.         StartCoroutine(ShowLaser());
  41.         CmdShowLaser();
  42.     }
  43.  
  44.     [Command]
  45.     void CmdDoShotSomeone(GameObject fromPlayer, GameObject hitPlayer)
  46.     {
  47.         hitPlayer.GetComponent<HealthAndDamage>().TakeDamage(fromPlayer);
  48.     }
  49.  
  50.     [Command]
  51.     void CmdShowLaser()
  52.     {
  53.         RpcShowLaser();
  54.     }
  55.  
  56.     [ClientRpc]
  57.     void RpcShowLaser()
  58.     {
  59.         if(isLocalPlayer) return;
  60.         StartCoroutine(ShowLaser());
  61.     }
  62.  
  63.     IEnumerator ShowLaser()
  64.     {
  65.         laser.enabled = true;
  66.  
  67.         yield return new WaitForSeconds(0.1f);
  68.         laser.enabled = false;
  69.     }
  70.  
  71.     public bool canFire {
  72.         get {return Time.time >= nextFireTime;}
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement