Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- constexpr int WINDOW_WIDTH = 800;
- constexpr int WINDOW_HEIGHT = 600;
- // The Ball class represents the ball that moves across the screen.
- class Ball {
- public:
- // The ball's position and radius are set in the constructor.
- Ball(float x, float y, float radius)
- : m_position(x, y)
- , m_radius(radius)
- {
- // Initialize the ball's velocity to a random value.
- m_velocity.x = -200.0f + rand() % 400;
- m_velocity.y = -200.0f + rand() % 400;
- }
- // The ball's position and velocity are updated in each frame.
- void update(float dt)
- {
- // Update the ball's position based on its velocity and the time passed.
- m_position += m_velocity * dt;
- // Check for collision with the walls.
- if (m_position.x - m_radius < 0.0f) {
- m_velocity.x = -m_velocity.x;
- m_position.x = m_radius;
- } else if (m_position.x + m_radius > WINDOW_WIDTH) {
- m_velocity.x = -m_velocity.x;
- m_position.x = WINDOW_WIDTH - m_radius;
- }
- if (m_position.y - m_radius < 0.0f) {
- m_velocity.y = -m_velocity.y;
- m_position.y = m_radius;
- } else if (m_position.y + m_radius > WINDOW_HEIGHT) {
- m_velocity.y = -m_velocity.y;
- m_position.y = WINDOW_HEIGHT - m_radius;
- }
- }
- // The ball is drawn to the screen using its position and radius.
- void draw(sf::RenderWindow& window)
- {
- sf::CircleShape shape(m_radius);
- shape.setPosition(m_position);
- shape.setFillColor(sf::Color::White);
- window.draw(shape);
- }
- private:
- // The ball's position, velocity, and radius are stored as member variables.
- sf::Vector2f m_position;
- sf::Vector2f m_velocity;
- float m_radius;
- };
- // The Paddle class represents the players' paddles.
- class Paddle {
- public:
- // The paddle's position, size, and speed are set in the constructor.
- Paddle(float x, float y, float width, float height, float speed)
- : m_position(x, y)
- , m_size(width, height)
- , m_speed(speed)
- {
- }
- // The paddle's position is updated based on user input.
- void update
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement