gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Beginners > ball and paddle collisions

#98217 - jbrain - Mon Aug 14, 2006 5:16 am

hello, would someone help me rewrite this bit of code...

Code:

///////////////////////////////////////////////////////////////
// check ball collision with paddle  REWRITE SOON!!!
   if(b_xpos > p_xpos && b_xpos+8 < p_xpos +32)
   {
      if ((b_ypos+8) > (p_ypos))
      {
         b_yvel = -b_yvel; // negatize the balls (y) velocity
         b_ypos += b_yvel; // update the balls (y) position
      }
   }
///////////////////////////////////////////////////////////////


b_xpos represents the ball and p_xpos represents the paddle etc...

The ball is an 8x8 sprite and the paddle is 8x32.
I havent done any programming in a few years so im a little new to this again. Any help would be great.

#98220 - sajiimori - Mon Aug 14, 2006 5:51 am

Hint: Try rewriting it using variable names like "ball_left" and "ball_right", etc. It'll probably be obvious then.

#98221 - jbrain - Mon Aug 14, 2006 6:04 am

what about bounding box collision? would that be appropriate? I dont think i understand what your saying.

#98317 - sajiimori - Mon Aug 14, 2006 5:38 pm

You are trying to do a bounding box check, right? If so, it will be easier to visualize the solution if you arrange your code like this:
Code:

bool collideBallPaddle()
{
  // Left side of the ball.
  int ball_left = ...

  // Right side of the ball.
  int ball_right = ...

  // More for top and bottom of the ball,
  // plus all sides of the paddle.
  ...

  // Use those variables to decide if they're colliding.
  // For instance, they can't be colliding if the right side
  // of the ball is to the left of the left side of the paddle.
  // Return true if they are, and false if they aren't.
}

In the long term, you'll want to make a Rectangle struct that holds the top-left and bottom-right (or top-left and width/height) of a rectangle, then write a generic collideRectangles function.

Someone will probably jump in and hand the solution to you, but you seem like the type who wants to solve things on your own. :)

#98355 - thegamefreak0134 - Mon Aug 14, 2006 9:30 pm

I'm not entirely sure I understand the problem. The code appears about as specific as it can get, and is short and to the point. If it works well, just re-name the names to stuff you know. For a game like pong or something similar with a paddle and ball, you won't be struggling very much with CPU time, so I'd personally say leave it as is if it works.

Perhaps I simply don't understand. What needs to be different about it?
_________________
What if the hokey-pokey really is what it's all about?

[url=http:/www.darknovagames.com/index.php?action=recruit&clanid=1]Support Zeta on DarkNova![/url]