我目前的实现如下:
if (shapesCollide) {
if (velocity.y > 0) entity.position.y = other.position.y - entity.size.y;
else entity.position.y = other.position.y + other.size.y;
velocity.y = 0;
if (velocity.x > 0) entity.position.x = other.position.x - entity.size.x;
else entity.position.x = other.position.x + other.size.x;
velocity.x = 0;
}然而,当移动发生在两个轴上时,这会导致奇怪的处理--例如,让entity向下移动到object的左边,然后移动它以与object碰撞,将正确地解决水平碰撞,但会破坏垂直运动。
我以前只是去
if (shapesCollide) {
position = oldPosition;
velocity = { 0, 0 };
}但这导致了另一个多轴问题:如果我的entity位于object上,它将无法移动,因为重力引起的运动会不断抵消两个速度。我也试着分别考虑两个轴,但这会导致问题,当碰撞发生时,两个速度都被考虑在内。
解决两轴碰撞的最佳方案是什么?
发布于 2019-02-19 09:41:36
我假设这些实体可以被认为或多或少是圆的,而这个大小就是实体的半径?
我们可能需要一点向量数学来解决这个问题。(我不知道c++中的平方根函数,所以请注意在sqrt。)尝试用这个替换if(shapesCollide)中的代码,看看它是如何为您工作的。
float rEntity = sqrt(entity.size.x * entity.size.x + entity.size.y * entity.size.y);
float rOther = sqrt(other.size.x * other.size.x + other.size.y * other.size.y);
float midX = (entity.position.x + other.position.x) / 2.0;
float midY = (entity.position.y + other.position.y) / 2.0;
float dx = entity.position.x - midX;
float dy = entity.position.y - midY;
float D = sqrt(dx * dx + dy * dy);rEntity和rOther是物体的半径,midX和midY是它们的中心坐标。dx和dy是从实体到中心的距离。
那就做:
entity.position.x = midX + dx * rEntity / D;
entity.position.y = midY + dy * rEntity / D;
other.position.x = midX - dx * rOther / D;
other.position.y = midY - dy * rOther / D;您可能应该检查D不是0,如果是,只需设置dx = 1,dy = 0,D=1或类似的东西。
你还应该继续这样做:
velocity.x = 0;
velocity.y = 0;如果你想让实体停止。
为了更准确地建模,您还可以尝试以下方法:
float rEntity = sqrt(entity.size.x * entity.size.x + entity.size.y * entity.size.y);
float rOther = sqrt(other.size.x * other.size.x + other.size.y * other.size.y);
float midX = (entity.position.x * rOther + other.position.x * rEntity) / (rEntity + rOther);
float midY = (entity.position.y * rOther + other.position.y * rEntity) / (rEntity + rOther);
float dxEntity = entity.position.x - midX;
float dyEntity = entity.position.y - midY;
float dEntity = sqrt(dxEntity * dxEntity + dyEntity * dyEntity);
float dxOther = other.position.x - midX;
float dyOther = other.position.y - midY;
float dOther = sqrt(dxOther * dxOther + dyOther * dyOther);
entity.position.x = midX + dxEntity * rEntity / dEntity;
entity.position.y = midY + dyEntity * rEntity / dEntity;
other.position.x = midX + dxOther * rOther / dOther;
other.position.y = midY + dyOther * rOther / dOther;它在考虑半径时找到中点。但我不能保证那行得通。此外,最后增加的迹象也很重要。
我希望这能帮上忙。如果有什么不清楚的话请告诉我。
https://stackoverflow.com/questions/54738171
复制相似问题