Unity 矩形攻击
2D游戏可以通过计算两个物体的距离与与半径比较,判断相交,相切,相离。
- pos2-pos1<r2+r1(相交)
- pos2-pos1=r2+r1(相切)
- pos2-pos1>r2+r1(相离)
3D游戏物理引擎消耗性能,尤其是在移动端设备上。
需要用到的数学知识点乘
A.B=|A|.|B|cos
如果B是单位向量,那么点乘就是A在B上的投影,相反就是B在A上的投影,如果A,B都为单位向量,那么得到就是cos值,根据这些知识可以判断两个物体是否相撞。
如图
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RectA : MonoBehaviour
{
public bool AttackRectJudge(Transform attacker,Transform attacked,float forwardDistance,float rightDistanse)
{
//计算两个物体之间的距离
Vector3 deltaA = attacker.position - attacked.position;
//计算delaA在攻击者上的投影
float forwardDot = Vector3.Dot(attacker.forward, deltaA);
//如果点乘大于零,说明被攻击者在攻击者的前方,
if (forwardDot > 0 && forwardDot<=forwardDistance)
{
//delaA在攻击者右方的投影
float rightDot = Math.Abs(Vector3.Dot(attacker.right, deltaA));
if (rightDot<=rightDistanse)
{
//发生了碰撞
return true;
}
return false;
}
return false;
}
}