UnityCommon/Role/Attack.cs
2024-12-14 23:20:36 +08:00

122 lines
4.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class Attack : MonoBehaviour
{
[Header("子弹预制体")] public GameObject bulletPrefab;
[Header("子弹数据")] public BulletData bulletData;
[Header("角色对象")] public Role role;
[Header("攻击范围")] public float attackScope;
[Header("攻击类型")] public DamageType damageTyp = DamageType.noAttributeDamage;
[Header("攻击冷却时间(秒)")] public float attackCooldown = 1f; // 攻击冷却时间
private float lastAttackTime = 0f; // 上次攻击的时间
[HideInInspector]
public List<GameObject> bulltes = new List<GameObject>();
public float AttackScope
{
[DebuggerStepThrough]
get => attackScope;
[DebuggerStepThrough]
set
{
attackScope = value;
GetComponent<CircleCollider2D>().radius = attackScope;
//Debug.Log("攻击半径"+GetComponent<CircleCollider2D>().radius);
}
}
public async void Start()
{
AttackScope = attackScope;
bulletData = new BulletData();
bulletData.BulletScattering = 1;
CircleCollider2D circleCollider2D = GetComponent<CircleCollider2D>();
while (true)
{
if (circleCollider2D)
{
// 检查是否可以进行攻击(基于冷却时间)
if (Time.time - lastAttackTime >= attackCooldown)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(circleCollider2D.transform.position, attackScope);
foreach (Collider2D collider in colliders)
{
Role targetRole = collider.GetComponent<Role>();
if (targetRole && targetRole.camp != role.camp)
{
role.animationHighlight = 1;
attack(targetRole);
lastAttackTime = Time.time; // 更新上次攻击时间
break; // 只攻击一个目标
}
else
{
role.animationHighlight = 0;
}
}
}
await Task.Delay(100); // 延迟,避免过于频繁地检测
}
else
{
return;
}
}
}
public void attack(Role targetRole)
{
if (bulletPrefab == null)
{
Debug.LogError("子弹预制体为空");
return;
}
Vector2 direction = (targetRole.transform.position - transform.position).normalized;
if (bulletPrefab.GetComponent<Bullet>().myBulletType == BulletType.Spraying)
{
GameObject BulletGamobj = GameObject.Instantiate(bulletPrefab, this.transform.root);
BulletGamobj.GetComponent<Bullet>().role = role;
BulletGamobj.GetComponent<Bullet>().attackObj = this;
// BulletGamobj.transform.up = direction;
BulletGamobj.transform.position = transform.position;
bulltes.Add(BulletGamobj);
return;
}
else
{
for (int i = 0; i < bulletData.BulletScattering; i++)
{
// 改变子弹方向,根据角色自身的攻击范围来计算
GameObject BulletGamobj = GameObject.Instantiate(bulletPrefab, this.transform.root);
BulletGamobj.GetComponent<Bullet>().role = role;
BulletGamobj.GetComponent<Bullet>().attackObj = this;
BulletGamobj.transform.up = direction;
BulletGamobj.transform.position = transform.position;
bulltes.Add(BulletGamobj);
}
}
}
private void OnDisable()
{
bulltes.Clear();
}
}