主要介绍AABB碰撞检测下,矩形该如何和矩形进行碰撞检测/和圆形进行碰撞检测。
直接看图,主要是比较两个矩形的边界线的前后关系。
效果
分析什么时候重合
分析什么时候不重合
完整代码
矩形身上挂载
public class Rectangle : MonoBehaviour
{
public float width;
public float heigth;
private Color showColor;
public Vector3 leftDownpoint { get; private set; }
public Vector3 rightUppoint { get; private set; }
private Vector3 leftUppoint;
private Vector3 rightDownpoint;
// Start is called before the first frame update
void Start()
{
showColor = Color.green;
RectangleCollisonManager.GetInstance().RegistCollider(this);
}
public void Detect(Vector3 leftDownPoint, Vector3 rightUpPoint)
{
if(this.rightUppoint.x < leftDownPoint.x || rightUpPoint.x < this.leftDownpoint.x || this.rightUppoint.y < leftDownPoint.y || rightUpPoint.y < this.leftDownpoint.y)
{
showColor = Color.green;
return;
}
showColor = Color.red;
}
// Update is called once per frame
void Update()
{
leftDownpoint = transform.position;
leftUppoint = transform.position + transform.up * heigth;
rightDownpoint = transform.position + transform.right * width;
rightUppoint = transform.position + transform.right * width + transform.up * heigth;
DrawRectangle();
}
void DrawRectangle()
{
Debug.DrawLine(leftDownpoint, leftUppoint, showColor);
Debug.DrawLine(leftDownpoint, rightDownpoint, showColor);
Debug.DrawLine(leftUppoint, rightUppoint, showColor);
Debug.DrawLine(rightUppoint, rightDownpoint, showColor);
}
}
负责让所有矩形互相进行检测
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RectangleCollisonManager : BaseManager<RectangleCollisonManager>
{
private List<Rectangle> RectangleCollider;
public void Init()
{
}
public void RegistCollider(Rectangle r)
{
if(RectangleCollider == null)
{
RectangleCollider = new List<Rectangle>();
}
RectangleCollider.Add(r);
}
public void Update()
{
DetectCollision();
}
void DetectCollision()
{
for (int i = 0; i < RectangleCollider.Count; i++)
{
for(int j = 0 ; j < RectangleCollider.Count; j++)
{
if (j != i)
{
RectangleCollider[i].Detect(RectangleCollider[j].leftDownpoint, RectangleCollider[j].rightUppoint);
}
}
}
}
}
tickManger调用管理器的tick,挂载在场景任意物体上面
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TickManager : MonoBehaviour
{
private RectangleCollisonManager m_rectangleCollisonManager;
// Start is called before the first frame update
void Start()
{
m_rectangleCollisonManager = RectangleCollisonManager.GetInstance();
m_rectangleCollisonManager.Init();
}
// Update is called once per frame
void Update()
{
m_rectangleCollisonManager.Update();
}
}
单例基类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseManager<T> where T : new()
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
{
instance = new T();
return instance;
}
else
{
return instance;
}
}
}