0
\$\begingroup\$

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?

\$\endgroup\$
4
  • \$\begingroup\$ You need to post your repositioning code. Also, what game engine are you using? Gosu is pretty good. \$\endgroup\$
    – ashes999
    Jun 14, 2014 at 14:50
  • \$\begingroup\$ @ashes yes I'm using gosu, but how would the full code help? \$\endgroup\$
    – Mohammad
    Jun 14, 2014 at 14:56
  • \$\begingroup\$ 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. \$\endgroup\$
    – ashes999
    Jun 14, 2014 at 15:36
  • \$\begingroup\$ @ashes999 I'm only reversing the direction of the ball: @ball.vy *= -1, nothing more. \$\endgroup\$
    – Mohammad
    Jun 14, 2014 at 15:48

1 Answer 1

1
\$\begingroup\$

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).

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

You must log in to answer this question.

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