Advertisement
Munchy2007

Unet5Tut6Pt2PlayerShoot

Feb 28th, 2016
5,890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 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.     int score;
  10.  
  11.     public override void OnStartLocalPlayer ()
  12.     {
  13.         enabled = true;
  14.     }
  15.  
  16.     public override void OnStartClient ()
  17.     {
  18.         laser = transform.Find("Laser").GetComponent<LineRenderer>();
  19.         laser.enabled = false;
  20.         enabled = false;
  21.     }
  22.  
  23.     void Update () {
  24.         if(Input.GetAxis("Fire1") != 0 && canFire)
  25.         {
  26.             nextFireTime = Time.time + fireRate;
  27.             Fire();
  28.         }
  29.     }
  30.  
  31.     void Fire()
  32.     {
  33.         Ray ray = new Ray(laser.transform.position,transform.forward);
  34.         RaycastHit hit;
  35.         if(Physics.Raycast(ray, out hit, 10f))
  36.         {
  37.             var hitPlayer = hit.collider.gameObject;
  38.             CmdDoShotSomeone(gameObject, hitPlayer);
  39.         }
  40.  
  41.         StartCoroutine(ShowLaser());
  42.         CmdShowLaser();
  43.     }
  44.  
  45.     [Command]
  46.     void CmdDoShotSomeone(GameObject fromPlayer, GameObject hitPlayer)
  47.     {
  48.         hitPlayer.GetComponent<HealthAndDamage>().TakeDamage(fromPlayer);
  49.     }
  50.  
  51.     [Command]
  52.     void CmdShowLaser()
  53.     {
  54.         RpcShowLaser();
  55.     }
  56.  
  57.     [ClientRpc]
  58.     void RpcShowLaser()
  59.     {
  60.         if(isLocalPlayer) return;
  61.         StartCoroutine(ShowLaser());
  62.     }
  63.  
  64.     IEnumerator ShowLaser()
  65.     {
  66.         laser.enabled = true;
  67.  
  68.         yield return new WaitForSeconds(0.1f);
  69.         laser.enabled = false;
  70.     }
  71.  
  72.     public bool canFire {
  73.         get {return Time.time >= nextFireTime;}
  74.     }
  75.  
  76.     [Server]
  77.     public void AddScore()
  78.     {
  79.         RpcAddScore();
  80.     }
  81.  
  82.     [ClientRpc]
  83.     void RpcAddScore()
  84.     {
  85.         if(isLocalPlayer)
  86.         {
  87.             score+=5;
  88.             HUD.instance.DisplayScore(score);
  89.         }
  90.     }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement