我的Monogame / C#项目中有一个工作碰撞系统,它使用四叉树来确定潜在的碰撞,并相应地测试它们。我的问题是我希望能够向实体发送一个方法(已经与之相撞),OnCollisionEnter()或OnCollisionStay(),具体取决于前一帧中是否存在冲突。
在以下代码中,永远不会调用OnCollisionEnter():
public class Collision : iSystem
{
private List<Entity> currentCollisions; // Collisions occurring in the current frame
private List<Entity> previousCollisions; // Collisions from the previous frame
public override void Initialize(Entity caller)
{
currentCollisions = new List<Entity>();
previousCollisions = new List<Entity>();
base.Initialize(caller);
hasInitialized = true;
}
public override void Update(GameTime gameTime)
{
List<Entity> nearby = Global.QuadTree.GetNeighbours(parent);
for (int i = 0; i < nearby.Count; i++)
{
if (nearby[i] != parent)
if (parent.Collider.Intersects(nearby[i].Collider))
{
currentCollisions.Add(nearby[i]);
AlertEntity(nearby[i]);
}
}
previousCollisions = currentCollisions; // Ready for the next frame
currentCollisions.Clear();
base.Update(gameTime);
}
public void AlertEntity(Entity entity)
{
if (previousCollisions.Contains(entity))
parent.OnCollisionStay(entity.Collider);
else
parent.OnCollisionEnter(entity.Collider); // This is never called
}
}
('parent'指的是组件'Collision'附加到的实体)
如果你能说明为什么会这样,我将不胜感激。谢谢
答案 0 :(得分:1)
调用currentCollisions.Clear()
也会清除previousCollisions
,因为它们都引用相同的List
对象。您应该将其设置为currentCollisions.Clear()
。
new List<Entity>()
// . . .
previousCollisions = currentCollisions; // Ready for the next frame
currentCollisions = new List<Entity>(); // Now both lists are not clear
base.Update(gameTime);