The SDL forums have moved to discourse.libsdl.org.
This is just a read-only archive of the previous forums, to keep old links working.


SDL Forum Index
SDL
Simple Directmedia Layer Forums
bounce code
spiff88


Joined: 23 Aug 2012
Posts: 6
so i've got this ball that i'd like to bounce off a paddle however the ball isnt effected at all by the paddle upon collision, I think it may have to do with pointers but i could be something else

ball class:
Code:

bool CBall::mCollision(CPaddle* other)
{
   if((mY >= other->mGetY() +other->mGetH()) && (mX >= other->mGetX() + other->mGetW()) &&
      (mY + mH <= other->mGetY()) && (mX + mW <= other->mGetX()))
      return true;
}

void CBall::mBounce(CPaddle* other)
{
   if(CBall::mCollision(other))
   {
   if(mDirection>=0 && mDirection<90)
   {
      if(mY + mH <= other->mGetY())
         mDirection = 270 + ((270 - mDirection) * 2);
      if(mX + mW <= other->mGetX())
         mDirection = 180 - ((0 + mDirection) * 2);
   }
   if(mDirection>=90 && mDirection<180)
   {
      if(mY + mH <= other->mGetY())
         mDirection = 270 + ((270 - mDirection) * 2);
      if(mX >= other->mGetX() + other->mGetW())
         mDirection = 0 - ((0 + mDirection) * 2);
   }
   if(mDirection>=180 && mDirection<270)
   {
      if(mY >= other->mGetY() + other->mGetH())
         mDirection = 90 + ((270 - mDirection)*2);
      if(mX >= other->mGetX() + other->mGetW())
         mDirection = 0 - ((mDirection - 180)*2);
   }
   if(mDirection>=270 && mDirection<360)
   {
      if(mY >= other->mGetY() + other->mGetH())
         mDirection = 90 - ((mDirection - 270)*2);
      if(mX + mW <= other->mGetX())
         mDirection = 180 + ((360 - mDirection)*2);
   }
   }
}


paddle class:

Code:

int CPaddle::mGetX()
{
   return mX;
}
int CPaddle::mGetY()
{
   return mY;
}

int CPaddle::mGetW()
{
   return mW;
}
int CPaddle::mGetH()
{
   return mH;
}


main:

Code:

// instantiate objects
CPaddle  mPlayer(10, (SCREEN_HEIGHT/2) - 30, 20, 60, 0xff, 0xff, 0xff, 5);
CBall   mBall;

// logic
mBall.mBounce(&mPlayer);


this is all the code related to the bounce function i believe, everything else works besides this bounce function(IDK why?), I'm able to get the ball to bounce off the screen borders so I know the bounce math is good just getting the ball to react to a collision with an object with changable x and y seems to be the problem
bala_48225


Joined: 01 Feb 2010
Posts: 48
Passing a pointer to a class into another class is a bad idea. You would do better to pass a constant reference to the class:

Code:
bool CBall::mCollision(const CPaddle& other)


and then redefine the paddle's accessor as a const accessor:

Code:
int CPaddle::mGetX() const
{
   return mX;
}


Passing a pointer to a class like that, or as I used to do, passing a non-const reference, will mangle your data sooner or later. Especially if there is a pointer inside the class.