球形圈内扇形攻击实例
一.运用的知识点
1).Physics.OverlapSphere(位置,半径)
参数物体的位置和球的半径,球形范围,用碰撞框的istigger也可以检测,只不过其返回值是 Collider [ ] x ,得到的是碰撞框数组
2).扇形攻击代码段
private bool UmbrellaAttact( Transform attacker ,Transform attacked ,float angle, float radius) { Vector3 deltaA = attacked.position - attacker.position; float tmpAngle = Mathf.Acos(Vector3.Dot(deltaA.normalized, attacker.forward)) * Mathf.Rad2Deg; if (tmpAngle < angle * 0.5f && deltaA.magnitude < radius) { return true; } return false; }
UmbrellaAttact传入参数(攻击者的transform,被攻击对象的transfor,扇形攻击的角度,扇形攻击的半径),返回值是bool类型!
3).
二.实例
第一段:
1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4
5 public class S4Player : MonoBehaviour {
6 void Start ()
7 {
8 }
9 void Update ()
10 {
11 if (Input.GetKeyDown(KeyCode.P))
12 {
13 AttackEnemy();
14 }
15 }
16 void AttackEnemy()
17 {
18 //获取在圈圈里面的人物
19 Collider[] _colliders= Physics.OverlapSphere(transform.position, 5);
20 // 符合要求的敌人列表
21 List<GameObject> AttackdList = new List<GameObject>();
22 //筛选完毕
23 foreach (var v in _colliders)
24 {
25 //判断是否在攻击角度里面
26 if (UmbrellaAttact(transform, v.transform, 60, 5))
27 {
28 AttackdList.Add(v.gameObject);
29 Debug.LogError(v.name);
30 }
31 }
32 //进行伤害计算
33 foreach (GameObject o in AttackdList)
34 {
35 //获取距离
36 float dis = Vector3.Distance(transform.position, o.transform.position);
37 //计算减血数值多少
38 float blood = 5 * 10 / dis;
39 //进行减血,调用敌人(第二段)身上的脚本
40 o.GetComponent<S4Enemy>().Attacked(blood);
41 }
42 }
43
44 private bool UmbrellaAttact( Transform attacker ,Transform attacked ,float angle, float radius)
45 {
46 Vector3 deltaA = attacked.position - attacker.position;
47 float tmpAngle = Mathf.Acos(Vector3.Dot(deltaA.normalized, attacker.forward)) * Mathf.Rad2Deg;
48 if (tmpAngle < angle * 0.5f && deltaA.magnitude < radius)
49 {
50 return true;
51 }
52 return false;
53 }
54 }
第二段:
1 public class S4Enemy : MonoBehaviour 2 { 3 public void Attacked(float Attackedblood) 4 { 5 Debug.LogWarningFormat("我是{0} 我掉血{1}",name,Attackedblood); 6 } 7 }
---恢复内容结束---