【发布时间】:2026-01-30 11:45:01
【问题描述】:
我正在开发一个简单的 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 的 cmets,我确实需要确保弹丸正确反弹,如果它们的速度恰好在单个游戏循环中穿过障碍物,我无法让它们穿过障碍物迭代。
在这种情况下,我想我需要针对所有障碍(可能重复)测试起点、速度、方向,直到不再有速度的交叉点。比如:
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;
}
是的,这已经有点棘手了。
谢谢
【问题讨论】:
-
您需要帮助的哪一部分?碰撞本身还是反射?或者两者兼而有之?
-
好吧,我也不知道该怎么做(代码示例或链接会很棒),但更多的是寻找一般的是/否,如果这是这样做的。
-
这是一个非常开放的问题