Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class Shooting : MonoBehaviour
- {
- [SerializeField] private Bullet _bulletPrefab;
- [SerializeField] private Transform _bulletsContainer;
- [SerializeField] private float _rayMaxDistance = 50f;
- private Camera _camera;
- private Transform _transform;
- private void Awake()
- {
- _camera = Camera.main;
- _transform = transform;
- }
- private void Update()
- {
- if (Input.GetMouseButtonDown(0))
- {
- Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ray, out RaycastHit hit, _rayMaxDistance))
- SpawnBullet(hit.transform);
- }
- }
- private void SpawnBullet(Transform target)
- {
- Vector3 position = _transform.position;
- Vector3 directionToTarget = (target.position - position).normalized;
- Bullet bullet = Instantiate(_bulletPrefab, position, Quaternion.identity, _bulletsContainer);
- bullet.Setup(directionToTarget);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment