游戏项目里常会遇到的判断敌人是否在我方英雄攻击范围。
有的英雄攻击范围是扇形,这时单纯用Collider或距离检测就不合适了,需要用到Vector3.Angle来检测角度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using UnityEngine; using System.Collections; public class NewBehaviourScript : MonoBehaviour { public Transform target; // 判断的敌人目标 public float angle = 90; public float distance = 2; // Use this for initialization void Start () { } // Update is called once per frame void Update () { // 判断距离 bool isInDistance = Vector3.Distance(transform.position, target.position) < distance; // 判断角度 bool isInAngle = Vector3.Angle(transform.forward, target.position - transform.position) < angle / 2; Debug.Log("距离:" + Vector3.Distance(transform.position, target.position) + " 角度:" + Vector3.Angle(transform.forward, target.position - transform.position)); if (isInDistance && isInAngle) { Debug.LogError("在攻击范围内"); } } } |
- 本文固定链接: http://www.u3d8.com/?p=1207
- 转载请注明: 网虫虫 在 u3d8.com 发表过