我正在做一个简单的2D游戏(鸟瞰图)。我有射弹,它们是圆圈。围绕游戏关卡存在障碍,这些都是矩形(轴对齐)。我希望弹丸在碰撞时能够从障碍物上弹开。我不知道如何在我的游戏循环中实现这一点。猜测它会是这样的:游戏循环中的碰撞检测?
void gameLoop() {
Projectile p = ..;
p.updateLocation(p.getVelocity(), p.getDirection());
Barrier intersected = p.intersects(barriers);
if (intersected != null) {
// We hit a barrier after moving on this time tick.
// Figure out where our reflected location off the
// barrier should be now.
Point ptNew = intersected.reflect(p.getLastPoint(), p.getVelocity(),
p.getDirection());
// Our new location after getting bounced off the barrier.
ptNew.setLocation(ptNew);
}
}
所以当我们移动弹丸,我们可以检查,如果我们相交(或完全内)的障碍之一。如果是这样,做一个计算,找出我们的反射位置应该离开我们的起点和速度/方向的障碍。
感谢
----------更新------------------------
小更具体一点 - 考虑到Erik的评论,我确实需要确保弹丸正常弹跳,如果它们的速度恰好如此之快,我们就不能让它们通过障碍,它们会在单个游戏循环迭代中顺利完成。在这种情况下,我想我需要测试一个起点,速度,方向,对所有障碍(可能反复),直到不再有可能的速度交点。例如:
void gameLoop() {
Projectile p = ...;
Barrier barrier = moveProjectile(p, barriers);
while (barrier != null && p.stillHasVelocityThisFrame()) {
barrier = moveProjectile(p, barriers);
}
// at this point, the projectile is done moving/bouncing around.
}
void moveProjectile(Projectile projectile,
List<Barrier> barriers)
{
for (Barrier barrier : barriers) {
// tbd
Barrier intersected = test2dVectorAgainstRectangle(
projectile.getPosition(),
projectile.get2dVector());
// the above would test the projectile's vector
// to see if it intersects any barrier, reflect
// off of it if necessary, modify the projectile's
// position, and reduce the available distance it
// can still travel for this frame.
if (intersected) {
return intersected;
}
}
// no intersections.
return null;
}
是的,这已经变得棘手。
感谢
其中的这部分,你需要帮助的?碰撞本身还是反射?或者两者兼得? – MGZero
嗯,我不知道该怎么做(代码示例或链接会很棒),但是如果这是如何完成的话,更多的是寻找一般性的yes/no。 – user291701
这是一个非常开放的问题 – Erik