I made a clone of the popular game breakout. The problem with it right now is that the ball only reflects at forty-five
degree angles, and I wish for it to reflect differently depending on where you hit the ball on the paddle. My idea was as
follows:
First of all, I want to constrain the paddle from -PI to PI in length, and as the paddle has varying lengths, I''ve decided
that this would work
x1/length_of_half_paddle = x2/PI
X1 = ball_collision_x_coordinate - paddle_center
I then simplify to this for x2
x2 = (x1 * PI)/length_of_half_paddle
if x1 is negative you''ll recieve somewhere in this range [-PI, 0]
if x1 is positive you''ll recieve somewhere in this range [0, PI]
All of this is in the first and second quadrant, so this should work. It is not though, I''ve erred somewhere.
I plug this into my function that calculates reflections based on the normal you wish to reflect from. I take the cos of the
calculated x2 for my x-coordinate of my normal and the sin of the calculated x2 for my y-coordinate of my normal to reflect
from. I am using this algorithm for reflection:
void ball::reflect(double normal_x, double normal_y)
{
ball_vector temp_vect, temp_vect2;
double temp1;
temp1 = (current_direction.x * normal_x +
current_direction.y * normal_y)*2;
temp_vect.x = temp1 * normal_x;
temp_vect.y = temp1 * normal_y;
//
temp_vect2.x = current_direction.x - temp_vect.x;
temp_vect2.y = current_direction.y - temp_vect.y;
current_direction.x = temp_vect2.x;
current_direction.y = temp_vect2.y;
move_ball();
}
Here is the way I am calling it. Notice that x is actually the paddle center, Modifier is half of the paddle length.
void ball::collided_paddle(double x, double Modifier,
double top, double bottom)
{ //
if(current_position_y - radius - current_direction.y <= top &&
current_position_y + radius - current_direction.y >= top &&
current_position_x + radius >= x - Modifier &&
current_position_x - radius <= x + Modifier &&
in_motion == true)
{
reflect(cos((3.14159 * (current_position_x - x))/Modifier),
sin((3.14159 * (current_position_x - x))/Modifier));
sounds.play_sound(0);
}
}
The ball reflects correctly part of the time, but other times it goes downwards into the third or the fourth quadrant,
and I have yet to figure out why.