UnityCommon/Role/Attack.cs
2024-12-05 16:25:46 +08:00

85 lines
2.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
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;
public float AttackScope
{
[DebuggerStepThrough]
get => attackScope;
[DebuggerStepThrough]
set
{
attackScope = value;
GetComponent<CircleCollider2D>().radius = attackScope;
}
}
public async void Start()
{
bulletData = new BulletData();
bulletData.BulletScattering = 1;
while (true) {
CircleCollider2D circleCollider2D = GetComponent<CircleCollider2D>();
if (circleCollider2D)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, circleCollider2D.radius);
foreach (Collider2D collider in colliders)
{
Role targetRole = collider.GetComponent<Role>();
if (targetRole && targetRole.camp != role.camp)
{
Debug.Log("检测到碰撞器:" + collider.name);
attack(targetRole);
}
}
await Task.Delay((int)(1000));
}
else
{
return;
}
}
}
public void attack(Role targetRole)
{
if (bulletPrefab==null)
{
Debug.LogError("子弹预制体为空");
return;
}
Vector2 direction = (targetRole.transform.position - transform.position).normalized;
List<GameObject> bulltes= new List<GameObject>();
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);
}
Debug.Log(bulltes.Count);
//foreach (GameObject bullet in bulltes)
//{
//}
}
}