1
\$\begingroup\$

I'm making a Pong game and I'm just looking for a simple way to calculate a straight travelling path for the ball based on the angle of the ball. How would I go about implementing something like this? Here is my code right now:

public void UpdatePosition()
{
    //For now let's just implement a very primitive movement algorithm
    //TODO: Movement calculation based on angle of the ball
    ball.velocity = (ball.angle < Math.PI / 2) ? 5 : -5;
    ball.Point = new Point(ball.Point.X + ball.velocity, ball.Point.Y + ball.velocity2);

    //Check if the suggested point is beyond the boundaries of the window
    if (ball.Point.X > ball.view.Boundaries.Width || ball.Point.Y > ball.view.Boundaries.Height || ball.Point.X < 0 
        || ball.Point.Y < 0)
    {
        ball.Collision(CollisionType.Boundary); // If it does raise collision event
    }

    //Check if the new point collides with the hitbox of a player paddle
    if (ball.gameController.Players[0].Paddle.GetHitbox().Any(point => point.Equals(ball.Point)) ||
        ball.gameController.Players[1].Paddle.GetHitbox().Any(point => point.Equals(ball.Point)))
    {
        ball.Collision(CollisionType.Paddle);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ The angle of the ball relative to what? The surface of the paddle? \$\endgroup\$
    – Anko
    Commented Apr 18, 2014 at 14:27
  • \$\begingroup\$ Well yeah, the angle that the ball will move in. \$\endgroup\$ Commented Apr 18, 2014 at 14:39

1 Answer 1

2
\$\begingroup\$

Velocity is a 2-dimensional value, representing the speed in both the X and Y directions. I notice you have velocity and velocity2; it might make things easier to use a 2D vector for velocity, like you do for position.

To calculate the speed in the X and Y directions, just multiply your total speed by the cos (for the horizontal component) and sin (for the vertical component) of the angle.

ball.velocity = new Point(5 * cos(ball.angle), 5 * sin(ball.angle));

Then because your velocity is also a 2D vector, you can just do:

ball.Point = ball.Point + ball.velocity;
\$\endgroup\$
1
  • 1
    \$\begingroup\$ (Note that you probably want to scale velocity by time-since-last-frame when adding it to the point; v=dP/dT becomes deltaP = v*deltaT.) \$\endgroup\$ Commented Apr 18, 2014 at 16:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .