Bob

Bob

  • NA
  • 5
  • 2k

2D Pong Bounce Angle Questions

Nov 14 2010 6:23 PM
Hi everyone,

I'm fairly new to 2D gaming in C# but here goes...

I have a pong game created where the ball always bounces off the bats at correct angles. I want to incorporate some control of how the ball bounces. For example, if the ball's Y velocity is negative (the ball is moving UPWARDS) AND the bat on either side is moving DOWNWARDS, I want the ball to bounce back where it came from (reverse both x and y velocities).

My code is as follows:

if ((Velocity.X < 0 && collision(_player1)) || (Velocity.X > 0 && collision(_player2)))
{
        Velocity.X = -Velocity.X;

        //The above code works fine, the below code to reverse the ball is not working.
        //I believe the code itself is correct, but the 'bools' are not being updated
        //If I add '_isUpKeyPressed = true;' then it works, but I want it updated from parent class

       if (_isUpKeyPressed && Velocity.Y > 0 || _isDownKeyPressed && Velocity.Y < 0)
      {
              Velocity.Y = -Velocity.Y;
      }
}

The above code is in the Ball class (Ball.cs file) which is inherited from the parent class in ControlSprite.cs. The below code is in ControlSprite.cs.

public bool _isUpKeyPressed;
public bool _isDownKeyPressed;
public bool _isRightKeyPressed;
public bool _isLeftKeyPressed;

public void KeyDown(Keys keys)
{
      if (keys == _upKey)
      {
             _isUpKeyPressed = true;
      }
      //etc etc
}

The bool values become true when you hold down the correct key to move the bat. Any ideas of how to update the bool values in the inherited class?

Thanks for any help!

Answers (5)