软件编程
位置:首页>> 软件编程>> C#编程>> Unity3D实现攻击范围检测

Unity3D实现攻击范围检测

作者:BattleTiger  发布时间:2023-07-02 12:12:39 

标签:Unity3D,检测

本文实例为大家分享了Unity3D实现攻击范围检测的具体代码,供大家参考,具体内容如下

一、扇形攻击范围检测


using UnityEngine;
using System.Collections;

public class AttackCHeck : MonoBehaviour
{
//要攻击的目标
public Transform Target;
//扇形距离 攻击距离 扇形的半径
private float SkillDistance = 5;
//扇形的角度 也就是攻击的角度
private float SkillJiaodu = 60;

private void Update()
{
 //与敌人的距离
 float distance = Vector3.Distance(transform.position, Target.position);
 //玩家正前方的向量
 Vector3 norVec = transform.rotation * Vector3.forward;
 //玩家与敌人的方向向量
 Vector3 temVec = Target.position - transform.position;
 //求两个向量的夹角
 float jiajiao = Mathf.Acos(Vector3.Dot(norVec.normalized, temVec.normalized)) * Mathf.Rad2Deg;
 if (distance < SkillDistance)
 {
  if (jiajiao <= SkillJiaodu * 0.5f)
  {
   Debug.Log("在扇形范围内");
  }
 }
}
}

二、长方形范围攻击检测


using UnityEngine;
using System.Collections;

public class AttackCHeck : MonoBehaviour
{
//要攻击的目标
public Transform Target;

private void Update()
{
 //计算玩家与敌人的距离
 float distance = Vector3.Distance(transform.position, Target.position);
 //玩家与敌人的方向向量
 Vector3 temVec = Target.position - transform.position;
 //与玩家正前方做点积
 float forwardDistance = Vector3.Dot(temVec, transform.forward.normalized);
 if (forwardDistance > 0 && forwardDistance <= 10)
 {
  float rightDistance = Vector3.Dot(temVec, transform.right.normalized);

if (Mathf.Abs(rightDistance) <= 3)
  {
   Debug.Log("进入攻击范围");
  }
 }

}
}

三、半圆形攻击范围检测


using UnityEngine;
using System.Collections;

public class AttackCHeck : MonoBehaviour
{
//要攻击的目标
public Transform Target;
private void Update()
{
 //计算玩家与敌人的距离
 float distance = Vector3.Distance(transform.position, Target.position);
 //玩家与敌人的方向向量
 Vector3 temVec = Target.position - transform.position;
 //与玩家正前方做点积
 float forwardDistance = Vector3.Dot(temVec, transform.forward.normalized);
 if (forwardDistance > 0 && forwardDistance <= 10)
 {
  if (distance <= 5)
  {
   Debug.Log("进入攻击范围");
  }
 }
}
}

暂时就写三种吧!目前就遇到三种,以后遇到再更新.接下来介绍一下算法的核心知识点吧

其实这些小算法基本上用的全是向量的计算,向量的计算有两种

1.向量的点乘

–>A . B = |A| * |B| * cos θ
–>点乘应用

1).如果 让 A 等于单位向量 |A| ==1 c点积 等于 B 在 A 上的投影
2).如果 让 A B等于单位向量 arccos(a.b) == 夹角

2.向量的叉乘

–>A* B = C C就是A和B的法向量
–>叉乘应用

1).c 是有方向 。 通过 左手 定则 可以知道 C 的方向
2).所以叉乘一般是用来计算方向的
3).A 和 B 都是单位向量 arcsin(|A*B|) 等于 夹角

来源:https://blog.csdn.net/BattleTiger/article/details/77853675

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com