using System.Collections; using System.Collections.Generic; using UnityEngine; public class TargetShooter : MonoBehaviour { private List targets = new List(); private AudioSource audioSource; private Quaternion originalRotation; // 原本的旋轉角度 public float shootInterval = 1f; // 射擊間隔 public float rotationSpeed = 300f; // 旋轉速度 public AudioClip shootSound; // 射擊音效 public GameObject explosionEffect; // 爆炸效果 void Start() { audioSource = gameObject.AddComponent(); originalRotation = transform.rotation; // 儲存原本旋轉角度 } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { targets.Clear(); GameObject[] foundTargets = GameObject.FindGameObjectsWithTag("Target"); // 找到所有具有 Target 標籤的物件 targets.AddRange(foundTargets); StartCoroutine(ShootTargets()); } } private IEnumerator ShootTargets() { while (targets.Count > 0) { // 隨機選擇一個目標 int randomIndex = Random.Range(0, targets.Count); GameObject target = targets[randomIndex]; // 設定旋轉方向 Vector3 targetPosition = target.transform.position; Vector3 direction = targetPosition - transform.position; // 逐漸旋轉到目標 Quaternion targetRotation = Quaternion.LookRotation(direction); float timeElapsed = 0f; float rotationDuration = 1f; // 旋轉持續時間 while (timeElapsed < rotationDuration) { // 平滑旋轉 transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime); timeElapsed += Time.deltaTime; yield return null; // 等待下一幀 } Ray ray = new Ray(transform.position, direction); // 發射射線 RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.collider.CompareTag("Target")) { // 播放音效 audioSource.PlayOneShot(shootSound); // 顯示射線 Debug.DrawLine(ray.origin, hit.point, Color.red, 1f); // 生成爆炸效果 Instantiate(explosionEffect, hit.point, Quaternion.identity); // 移除目標物件 Destroy(target); targets.RemoveAt(randomIndex); } } yield return new WaitForSeconds(shootInterval); // 等待一段時間 } Debug.Log("全部擊中"); // 所有目標都被擊中後顯示訊息 float returnTimeElapsed = 0f; // 轉回原本的角度 float returnDuration = 1f; // 返回持續時間 while (returnTimeElapsed < returnDuration) { // 平滑旋轉回原本的角度 transform.rotation = Quaternion.RotateTowards(transform.rotation, originalRotation, rotationSpeed * Time.deltaTime); returnTimeElapsed += Time.deltaTime; yield return null; // 等待下一幀 } targets.Clear(); // 清空陣列內容 } }