2
« on: September 14, 2015, 08:14:28 pm »
Hi all,
I have recently started using sfml, and have encountered an issue while implementing collisions in a simple pong game
In the code below, the ball does not move even though it is supposed to, but instead just stays stationary
//Main.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "Player.h"
#include "ball.h"
int main();
sf::RenderWindow window(sf::VideoMode(720, 480), "Pong");
Player player(285, 420);
Ball ball(100, 500);
int main() {
player.setPos();
ball.setPos();
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(true);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear(sf::Color::Black);
window.draw(player.getrPlayer());
window.draw(ball.getBall());
player.update();
ball.ballCollisions(player.getrPlayer());
ball.update();
window.display();
}
return 0;
}
//ball.h
#pragma once
#include <SFML\Graphics.hpp>
class Ball {
public:
Ball(int x, int y);
sf::CircleShape getBall();
void setPos();
void ballMovement();
void update();
int xVel;
int yVel;
void ballCollisions(sf::RectangleShape rectangle);
private :
int x;
int y;
public:
int getX();
int getY();
int getXVel();
int getYVel();
};
//ball.cpp
#include "ball.h"
#include "Player.h"
sf::CircleShape ball(10);
int xVel = 5;
int yVel = 5;
Ball::Ball(int x, int y) {
this->x = x;
this->y = x;
}
int Ball::getX() { return x; }
int Ball::getY() { return y; }
sf::CircleShape Ball::getBall() {
return ball;
}
void Ball::setPos() {
ball.setPosition(x, y);
}
void Ball::ballMovement() {
ball.move(xVel, yVel);
}
void Ball::update() {
ballMovement();
}
int Ball::getXVel() { return xVel; }
int Ball::getYVel() { return yVel; }
void Ball::ballCollisions(sf::RectangleShape rectangle) {
if (ball.getGlobalBounds().intersects(rectangle.getGlobalBounds())) {
xVel *= -1;
yVel *= -1;
}
}