using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 扇型攻击检测,并绘制检测区域
///
public class SectorDetect : MonoBehaviour
{
public Transform attacked; //受攻击着
public LineRenderer line;
GameObject go;
MeshFilter mf;
MeshRenderer mr;
Shader shader;
void Start()
{
ToDrawSectorSolid(transform, transform.position, 30, 2.5f);
}
void Update()
{
// UmbrellaAttact(transform, attacked.transform, 60, 4);
go.transform.localPosition = transform.localPosition;
}
///
/// 扇形攻击范围
///
/// 攻击者
/// 被攻击方
/// 扇形角度
/// 扇形半径
///
public bool UmbrellaAttact(Transform attacker, Transform attacked, float angle, float radius)
{
Vector3 deltaA = attacked.position - attacker.position;
//Mathf.Rad2Deg : 弧度值到度转换常度
//Mathf.Acos(f) : 返回参数f的反余弦值
float tmpAngle = Mathf.Acos(Vector3.Dot(deltaA.normalized, attacker.forward)) * Mathf.Rad2Deg;
if (tmpAngle < angle * 0.5f && deltaA.magnitude < radius)
{
return true;
}
return false;
}
public void ToDrawSectorSolid(Transform t, Vector3 center, float angle, float radius)
{
int pointAmmount = 100;
float eachAngle = angle / pointAmmount;
Vector3 forward = transform.forward;
List vertices = new List();
Vector3[] linepos = new Vector3[pointAmmount];
vertices.Add(center);
for (int i = 0; i < pointAmmount; i++)
{
Vector3 pos = Quaternion.Euler(0f, -angle / 2 + eachAngle * (i - 1), 0f) * forward * radius + center;
vertices.Add(pos);
linepos[i] = pos;
}
line.positionCount = pointAmmount;
line.SetPositions(linepos);
line.SetPosition(0, transform.position);
line.SetPosition(line.positionCount - 1, transform.position);
CreateMesh(vertices);
}
private GameObject CreateMesh(List vertices)
{
int[] triangles;
Mesh mesh = new Mesh();
int triangleAmount = vertices.Count - 2;
triangles = new int[3 * triangleAmount];
//根据三角形的个数,来计算绘制三角形的顶点顺序
for (int i = 0; i < triangleAmount; i++)
{
triangles[3 * i] = 0;
triangles[3 * i + 1] = i + 1;
triangles[3 * i + 2] = i + 2;
}
if (go == null)
{
go = new GameObject("mesh");
//go.transform.SetParent(transform);
mf = go.AddComponent();
mr = go.AddComponent();
shader = Shader.Find("Unlit/Color");
}
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles;
mf.mesh = mesh;
mr.material.shader = shader;
mr.material.color = Color.red;
go.transform.SetParent(transform.parent);
return go;
}
}