Advertisement
Guest User

Untitled

a guest
Dec 7th, 2022
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2.  
  3. constexpr int WINDOW_WIDTH = 800;
  4. constexpr int WINDOW_HEIGHT = 600;
  5.  
  6. // The Ball class represents the ball that moves across the screen.
  7. class Ball {
  8. public:
  9.     // The ball's position and radius are set in the constructor.
  10.     Ball(float x, float y, float radius)
  11.         : m_position(x, y)
  12.         , m_radius(radius)
  13.     {
  14.         // Initialize the ball's velocity to a random value.
  15.         m_velocity.x = -200.0f + rand() % 400;
  16.         m_velocity.y = -200.0f + rand() % 400;
  17.     }
  18.  
  19.     // The ball's position and velocity are updated in each frame.
  20.     void update(float dt)
  21.     {
  22.         // Update the ball's position based on its velocity and the time passed.
  23.         m_position += m_velocity * dt;
  24.  
  25.         // Check for collision with the walls.
  26.         if (m_position.x - m_radius < 0.0f) {
  27.             m_velocity.x = -m_velocity.x;
  28.             m_position.x = m_radius;
  29.         } else if (m_position.x + m_radius > WINDOW_WIDTH) {
  30.             m_velocity.x = -m_velocity.x;
  31.             m_position.x = WINDOW_WIDTH - m_radius;
  32.         }
  33.  
  34.         if (m_position.y - m_radius < 0.0f) {
  35.             m_velocity.y = -m_velocity.y;
  36.             m_position.y = m_radius;
  37.         } else if (m_position.y + m_radius > WINDOW_HEIGHT) {
  38.             m_velocity.y = -m_velocity.y;
  39.             m_position.y = WINDOW_HEIGHT - m_radius;
  40.         }
  41.     }
  42.  
  43.     // The ball is drawn to the screen using its position and radius.
  44.     void draw(sf::RenderWindow& window)
  45.     {
  46.         sf::CircleShape shape(m_radius);
  47.         shape.setPosition(m_position);
  48.         shape.setFillColor(sf::Color::White);
  49.         window.draw(shape);
  50.     }
  51.  
  52. private:
  53.     // The ball's position, velocity, and radius are stored as member variables.
  54.     sf::Vector2f m_position;
  55.     sf::Vector2f m_velocity;
  56.     float m_radius;
  57. };
  58.  
  59. // The Paddle class represents the players' paddles.
  60. class Paddle {
  61. public:
  62.     // The paddle's position, size, and speed are set in the constructor.
  63.     Paddle(float x, float y, float width, float height, float speed)
  64.         : m_position(x, y)
  65.         , m_size(width, height)
  66.         , m_speed(speed)
  67.     {
  68.     }
  69.  
  70.     // The paddle's position is updated based on user input.
  71.     void update
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement