[英]XNA collision in 3D
我一直在尝试在程序中进行碰撞检测。 在我的程序中,立方体内有一个球。 我希望球在立方体内弹跳,如果我的立方体上有孔,我希望它掉下来。
我现在是如何做到“碰撞”的:
protected void Bounce()
{
if (ballPosition.X >= boxWidth || ballPosition.X <= -boxWidth)
modelVelocity.X *= -1;
if (ballPosition.Y >= boxHeight*4.18 || ballPosition.Y <= -boxHeight)
modelVelocity.Y *= -1;
if (ballPosition.Z >= boxLength || ballPosition.Z <= -boxLength)
modelVelocity.Z *= -1;
}
但这在我实施重力时效果不佳并且会出现故障。 它贯穿两侧。 它不会留在盒子里。 那么,如果存在倾斜的墙,如何检测碰撞并可能还检测角度,使其在某个方向反弹?
要检测球和盒子何时相交,可以分别对它们使用BoundingSphere和BoundingBox。 然后使用BoudningBox.Contains()方法和不同的一个遏制类型时,球和框边相交来检测。
举个例子:
void CollisionDetection()
{
if (!boxBoundingBox.Contains(ballBouningSphere, ContainmentType.Contains))
//if the box doesn't completely contain the ball they are overlapping
{
//Collision happened.
}
}
然后,对于孔,您可能想要创建一个自定义对象holes
,如果球和盒子重叠,则检查球是否在孔中,如果是,则取消碰撞。 这些只是一些想法。 高温超导
使用轴的逻辑:当X> targetX和X <targetX + width->确认X轴碰撞时。 但这并不意味着存在冲突:您必须对Y轴(对于3D以及Z轴)都做同样的事情,所以您得到:
public bool collision(Vector3 pos, Vector3 dimensions, Vector3 targetPos,
Vector3 targetDimensions)
{
return (pos.X + dimensions.X > targetPos.X &&
pos.X < targetPos.X + targetDimensions.X &&
pos.Y + dimensions.Y > targetPos.Y &&
pos.Y < targetPos.Y + targetDimensions.Y &&
pos.Z + dimensions.Z > targetPos.Z &&
pos.Z < targetPos.Z + targetDimensions.Z);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.