如何在SFML 2.5.0中的两个RectangleShapes之间发生碰撞? (C ++)

时间:2018-08-01 10:21:13

标签: c++ sfml

所以我对SFML编码还比较陌生,所以如果我犯了一些新手错误,就深表歉意。我的项目是SFML中的Space Invaders。当我进行拍摄时,出现了问题。如何碰撞?我对shape.getGlobalBounds()。intersect()很熟悉,并且可以在以前的项目中使用。没用所以我尝试简化它。我将RectangleShape用于敌人的形状和子弹的形状。

这是碰撞的实际for循环:

for (int y = 0; y <= 2; ++y) {
    for (int x = 0; x <= 6; ++x) {
        if (shootShape.getPosition().x < e.aliensX[x] && shootShape.getPosition().x > e.aliensX[x] + 15 ||
            shootShape.getPosition().y < e.aliensY[y] && shootShape.getPosition().y > e.aliensY[y] + 15) {
            e.aliensX[x] = -10;
            e.aliensY[y] = -10;
            shooting = false;
            reload = false;
        }
    }
}

这是拍摄功能:

void Player::shoot() {
    if (reload) {
        shootX = posX + 5;
        shootY = posY - 50;
        shootShape.setPosition(shootX, shootY);
        shooting = true;
        reload = false;
    }
    if (shooting) {
        shootY -= 150 * 2 * deltaTime;
        shootShape.setPosition(shootX, shootY);
    }
}

这就是我吸引敌人的方式(我不知道如何制造多个敌人):

void Enemy::drawAliens() {
    for (int j = 0; j <= arraySizeY; ++j) {
        for (int i = 0; i <= arraySizeX; ++i) {
            actualShape.setPosition(aliensX[i], aliensY[j]);
            if (aliensY[i] <= p.shootY && aliensY[i] >= p.shootY) {
                aliensX[i] = -10;
                aliensY[i] = -10;
            }
            else {
                win.draw(actualShape);
            }
        }
    }
}

一些变量后面的解释: AliensX是一个数组,其中包含敌人的不同x位置。 AliensY是一个数组,其中包含敌人的不同y位置。 射击是一个布尔变量,子弹行进时确实如此。 重新加载就是您是否可以射击。

编辑: 由于我创建敌人的方式,相交将不起作用。它们都是一个形状。我需要它与特定坐标配合使用,因为我不知道一种更好的方法来一次创建多个敌人。如果有办法的话,建议将不胜感激!

2 个答案:

答案 0 :(得分:2)

如果您依靠SFML的模板化sf::Rect类,这很容易。只需将两个对象的矩形作为全局边界并尝试相交即可:

const bool collides = firstDrawable.getGlobalBounds().intersect(secondDrawable.getGlobalBounds());`

可以使用一个小的临时矩形来完成相同的操作,您可以用不直接与sf::Drawable相关联的动态值填充:

const sf::FloatRect bullet(x - width / 2, y - height / 2, width, height);
const bool collides = firstDrawable.getGlobalBounds().intersect(bullet);`

答案 1 :(得分:0)

您的if语句永远不会为真。你有

shootShape.getPosition().x < e.aliensX[x] && shootShape.getPosition().x > e.aliensX[x] + 15. 

您的shootShape.getPosition().x永远不能小于e.aliensX[x]并且不能大于e.aliensX[x] + 15。这不可能。 y位置也一样。将您的if语句更改为

for (int y = 0; y <= 2; ++y) {
  for (int x = 0; x <= 6; ++x) {
    if (shootShape.getPosition().x > e.aliensX[x] && shootShape.getPosition().x < e.aliensX[x] + 15 ||
        shootShape.getPosition().y > e.aliensY[y] && shootShape.getPosition().y < e.aliensY[y] + 15) {
      e.aliensX[x] = -10;
      e.aliensY[y] = -10;
      shooting = false;
      reload = false;
    }
  }
}