mycj_demo/mycj/Assets/Script/Attack.cs
2024-12-02 23:38:32 +08:00

90 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attack : Palye
{
[Header("发射的子弹")]
public GameObject bullet;
[Header("射击间隔")]
public float attackInterval = 1f;
[Header("敌人Tag")]
public string enemyTag = "Enemy";
[Header("paotaInfo的脚本")]
public paotaInfo towerInfo; // 引用 paotaInfo 脚本
[Header("需要一个canvas作为生成子弹的父节点")]
public Canvas canvas;
[Header("子弹的飞行速度")]
public float bulletSpeed;
private float attackTimer = 0f;
// Start is called before the first frame update
void Start()
{
if (towerInfo == null)
{
Debug.LogError("未找到 paotaInfo 脚本,请检查挂载!");
}
}
// Update is called once per frame
void Update()
{
if (!transform.parent.CompareTag("paotai"))
{
return;
}
attackTimer += Time.deltaTime;
if (attackTimer >= attackInterval)
{
attackTimer = 0f;
CheckAndAttack();
}
}
private void CheckAndAttack()
{
if (towerInfo == null) return;
// 使用 CircleCollider2D 的范围检测敌人
Collider2D[] hits = Physics2D.OverlapCircleAll(transform.position, towerInfo._CircleCollider2D.radius);
foreach (var hit in hits)
{
if (hit.CompareTag(enemyTag))
{
Debug.Log("检测到敌人");
// 检测到敌人,开始射击
Shoot(hit.transform);
return; // 只攻击一个目标
}
}
}
private void Shoot(Transform target)
{
if (bullet != null)
{
// 创建子弹实例
GameObject newBullet = Instantiate(bullet, canvas.transform);
newBullet.transform.position = transform.position;
newBullet.GetComponent<bullet>().Init(target.gameObject, bulletSpeed);
newBullet.GetComponent<bullet>().user = this;
Debug.Log("射击敌人:" + target.name);
}
}
private void OnDrawGizmos()
{
// 可视化攻击范围,需确保 paotaInfo 已挂载
if (towerInfo != null)
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, towerInfo._CircleCollider2D.radius);
}
}
}