# Collision detection in ruby

I'm making a simple pong game in ruby.

I did the collision detection this way:

def collides_with(player)
((@x + @image.width >= player.x) && (@x <= player.x + player.image.width)) && ((@y + @image.height >= player.y) && (@y <= player.y + player.image.height))
end


If this is true I multiply the ball's y coordinate by -1 (to change its direction):

@ball.vy *= -1

This is working as expected, except in one case when the ball reaches the left (or right) side of the paddle while it's moving. this will cause the ball to move into the inside of the paddle,which seems strange.

What should I do to fix this?

• You need to post your repositioning code. Also, what game engine are you using? Gosu is pretty good. – ashes999 Jun 14 '14 at 14:50
• @ashes yes I'm using gosu, but how would the full code help? – Mhmd Jun 14 '14 at 14:56
• you're just showing how you detect collisions. You're not showing the part where you adjust the ball position when there's a collision. – ashes999 Jun 14 '14 at 15:36
• @ashes999 I'm only reversing the direction of the ball: @ball.vy *= -1, nothing more. – Mhmd Jun 14 '14 at 15:48

Thanks for the additional details. The answer appears actually really simple: you're bouncing the ball back upward via:

@ball.vy *= -1

In the normal case, the ball's velocity is positive (downward), it hits the top of the pedal, and becomes negative (upward).

But if the ball hits the side of the pedal, it might bounce back upward and immediately collide with the pedal again. In fact, it might do this multiple times (once per frame) within a second, and you would only see the final velocity when it's released.

The real fix for this is to look at where the ball hit the pedal (eg. sides) and adjust the velocity accordingly (eg. bounce sideways but retain downward velocity). A common solution to this is separating axis theory, which is usually good (but fails in some cases with really high velocity objects).

• Dude I just wrote my answer one minute ago, did you try it before marking it as accepted? – ashes999 Jun 14 '14 at 16:09
• thanks it worked, instead of multiplying the value by -1, I just set the value directly. @ball.vy = value – Mhmd Jun 14 '14 at 18:04
• Ok, great, glad I could help. – ashes999 Jun 14 '14 at 18:39