想知道是否有人可以帮我发现一个性能问题,因为我是C ++的新手。使用SFML处理pong游戏,现在只使用RectangleShape类,没有图像。
我正在进行延迟碰撞检查(没有四叉树)但是现在给它现场的两个对象,它不会引起问题:
游戏循环中的代码:
window.clear();
const float time = clock.getElapsedTime().asSeconds();
for (GameObject* object : gameObjects) {
object->update(input, time);
}
sf::FloatRect *paddleBounds = p.getBounds();
sf::FloatRect *ballBounds = b.getBounds();
if (paddleBounds->intersects(*ballBounds, intersection)) {
if (intersection.width > intersection.height) {
b.changeYDirection();
}
else {
b.changeXDirection();
}
collisionManger.correctOverlap(ballBounds, &intersection, b.getSpeed(), &correction);
}
checkForPoints(&b);
clock.restart();
for (GameObject* object : gameObjects) {
object->render(window);
}
检查积分(这可以看出是否应该得分)
void Game::checkForPoints(Ball *ball) {
bool ballOutOfBounds = false;
if (ball->getBounds()->left < 0) {
aiScore++;
ballOutOfBounds = true;
}
else if (ball->getBounds()->left > 800) {
playerScore++;
ballOutOfBounds = true;
}
if (ballOutOfBounds) {
ball->resetPosition();
}
}
碰撞经理:
void CollisionManager::correctOverlap(sf::FloatRect *rectone, sf::FloatRect *intersection, sf::Vector2f *velocity, sf::Vector2f *correction) {
if (intersection->width > intersection->height) {
if (velocity->y < 0) {
correction->y = velocity->y;
}
else if (velocity->y > 0) {
correction->y = -velocity->y;
}
}
else {
if (velocity->x < 0) {
correction->x = velocity->x;
}
else if (velocity->x > 0) {
correction->x = -velocity->x;
}
}
}
球更新:
void Ball::update(InputManager &im, float time) {
bounds.left += m_speed.x * time;
bounds.top += m_speed.y * time;
if (bounds.top < 0) {
bounds.top = 1;
changeYDirection();
}
else if (bounds.top > 600 - bounds.height) {
bounds.top = 600 - bounds.height - 1;
changeYDirection();
}
m_rect.setPosition(bounds.left, bounds.top);
}
现在大部分时间游戏运行顺畅。但偶尔球会跳过屏幕30-40像素。
changeYDirection和changeXDirection简单地将x / y值乘以速度向量的-1。
答案 0 :(得分:1)
所以这是一个与代码无关的愚蠢问题。在夜间将屏幕变暗的应用程序通量导致性能下降。