Reputation: 13611
Wondering if someone can help me spot a perf problem, as i'm new to C++. Working on pong game with SFML, just using the RectangleShape class for now, no images.
I'm doing lazy collision checking (no quad tree) but given it's two objects on scene right now, it shouldn't cause a problem:
Code inside my game loop:
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);
}
The check for points (this sees if there should be a scoring)
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();
}
}
The collision manager:
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;
}
}
}
And the ball update:
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);
}
Now for the most part the game runs smooth. But occasionally the ball skips across the screen by like 30-40 pixels.
The changeYDirection and changeXDirection simply multiplies the x/y values by -1 of the speed vector.
Upvotes: 0
Views: 65
Reputation: 13611
So this was a silly problem not related to the code at all. Flux the app that dims your screen orange at night time was causing the performance drop.
Upvotes: 1