Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Gun : MonoBehaviour {
- public float damage = 10f;
- public float range = 100f;
- public Transform gunEnd;
- [SerializeField]
- LayerMask mask;
- public ParticleSystem muzzleFlash;
- public LineRenderer gunRay;
- public float accuracy = 1f;
- float randomOffset_x;
- float randomOffset_y;
- float randomOffset_z;
- public GameObject gun;
- void Start(){
- gunRay.enabled = false;
- }
- void Update () {
- RaycastHit gunrayhit;
- Ray gunlookat = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2 ));
- if (Physics.Raycast (gunlookat, out gunrayhit, range)) {
- gun.transform.LookAt (gunrayhit.point);
- }
- if (Input.GetButtonDown ("Fire1")) {
- Shoot ();
- }
- }
- void Shoot(){
- randomOffset_x = UnityEngine.Random.Range(0, 1 - accuracy);
- randomOffset_y = UnityEngine.Random.Range(0, 1 - accuracy);
- randomOffset_z = UnityEngine.Random.Range(0, 1 -accuracy);
- Vector3 direction = transform.forward;
- direction.x += randomOffset_x;
- direction.y += randomOffset_y;
- direction.z += randomOffset_z;
- muzzleFlash.Play ();
- RaycastHit cameraHit;
- Ray cameraAim = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2 ));
- cameraAim.direction = direction;
- if (Physics.Raycast (cameraAim, out cameraHit, range, mask)) {
- Debug.DrawLine (cameraAim.origin, cameraHit.point, Color.green);
- Vector3 cameraHitPoint = cameraHit.point;
- float cameraDistance = cameraHit.distance ;
- if (Physics.Raycast (cameraAim, out cameraHit)) {
- RaycastHit playerHit;
- Ray ray = new Ray (gunEnd.transform.position, cameraHitPoint - gunEnd.transform.position);
- if (Physics.Raycast (ray, out playerHit, range)) {
- Debug.DrawRay (gunEnd.transform.position, cameraHitPoint - gunEnd.transform.position, Color.red);
- float playerDistance = playerHit.distance;
- Target target = playerHit.transform.GetComponent<Target> ();
- if (target != null) {
- target.TakeDamage (damage);
- }
- StartCoroutine (gunHit (playerHit));
- }
- }
- } else {
- Debug.DrawLine (cameraAim.origin, cameraAim.origin + cameraAim.direction * range, Color.green);
- StartCoroutine (gunMiss(cameraAim));
- }
- }
- IEnumerator gunHit(RaycastHit hit){
- gunRay.enabled = true;
- gunRay.SetPosition (0, gunEnd.position);
- gunRay.SetPosition (1, hit.point);
- yield return null;
- gunRay.enabled = false;
- }
- IEnumerator gunMiss(Ray ray){
- gunRay.enabled = true;
- gunRay.SetPosition (0, gunEnd.position);
- gunRay.SetPosition(1, ray.origin + ray.direction * range);
- yield return null;
- gunRay.enabled = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement