Advertisement
Pro_Unit

Shooting

Sep 22nd, 2022
863
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.02 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Shooting : MonoBehaviour
  4. {
  5.     [SerializeField] private Bullet _bulletPrefab;
  6.     [SerializeField] private Transform _bulletsContainer;
  7.     [SerializeField] private float _rayMaxDistance = 50f;
  8.     private Camera _camera;
  9.     private Transform _transform;
  10.  
  11.     private void Awake()
  12.     {
  13.         _camera = Camera.main;
  14.         _transform = transform;
  15.     }
  16.  
  17.     private void Update()
  18.     {
  19.         if (Input.GetMouseButtonDown(0))
  20.         {
  21.             Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
  22.  
  23.             if (Physics.Raycast(ray, out RaycastHit hit, _rayMaxDistance))
  24.                 SpawnBullet(hit.transform);
  25.         }
  26.     }
  27.  
  28.     private void SpawnBullet(Transform target)
  29.     {
  30.         Vector3 position = _transform.position;
  31.  
  32.         Vector3 directionToTarget = (target.position - position).normalized;
  33.  
  34.         Bullet bullet = Instantiate(_bulletPrefab, position, Quaternion.identity, _bulletsContainer);
  35.  
  36.         bullet.Setup(directionToTarget);
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement