Search code examples
c++sfmlpong

Moving a ball in SFML


I am making a ping pong game using SFML and the ball is a square. I looked at tutorials and for some reason I can't get my ball to move. I used cout statements to check the ball's position but it just outputs its initial position. I suspect there is something wrong with my math... but the ball should move.

void ball_traits(sf::RectangleShape ball, sf::RectangleShape leftPaddle)
{
    double ballSpeed = 5;
    int angle = 90;

    //Scale X and Y will give the angle
    double scaleX = cos(angle);
    std::cout << scaleX << std::endl;
    double scaleY = sin(angle);
    double velocityX = scaleX * ballSpeed;
    double velocityY = scaleY * ballSpeed;
    //take original position
    double moveX = ball.getPosition().x;
    double moveY = ball.getPosition().y;

    sf::Clock clock;
    double elapsed = clock.restart().asSeconds();

    moveX += velocityX  * elapsed;
    moveY += velocityY * elapsed;
    std::cout << moveX << std::endl;
    std::cout << moveY << std::endl;
    ball.move(moveX,  moveY);
}

I just want to be pushed in the right direction. This is my first game and my c++ skills are a little rusty. [Update] I forgot to pass the object by reference (face palm).


Solution

  • I think elapsed time is very very close to zero. It's zero. Yes. You should declare clock as a global variable.

    And you must use radian for sin and cos functions.