using System.Collections; using UnityEngine; // ReSharper disable once CheckNamespace namespace BlueWaterProject { public class ObjectWeapon : MonoBehaviour { [SerializeField] private LayerMask targetLayer; [SerializeField] private float power; [SerializeField] private float autoDestroyTime = 3f; private Rigidbody rb; private SphereCollider sphereCollider; private WaitForSeconds waitForSeconds; private void Awake() { rb = GetComponent(); sphereCollider = GetComponent(); waitForSeconds = new WaitForSeconds(autoDestroyTime); } private void OnDestroy() { StopAllCoroutines(); } private void Start() { StartCoroutine(nameof(AutoDestroy)); } private void FixedUpdate() { // if (rb.velocity.magnitude != 0) // { // transform.rotation = Quaternion.LookRotation(rb.velocity); // Sets rotation to look at direction of movement // } var direction = rb.velocity; // Gets the direction of the projectile, used for collision detection if (rb.useGravity) direction += Physics.gravity * Time.deltaTime; // Accounts for gravity if enabled direction = direction.normalized; var detectionDistance = rb.velocity.magnitude * Time.deltaTime; // Distance of collision detection for this frame if (Physics.SphereCast(transform.position, sphereCollider.radius, direction, out var hit, detectionDistance, targetLayer)) // Checks if collision will happen { transform.position = hit.point + (hit.normal); // Move projectile to point of collision Destroy(gameObject); // Removes the projectile hit.transform.GetComponent()?.TakeDamage(power); } } private IEnumerator AutoDestroy() { yield return waitForSeconds; if (gameObject != null) { Destroy(gameObject); } } public void SetPower(float value) => power = value; } }