Pong Hit Detection

Started by
12 comments, last by JDCAce 11 years, 6 months ago
EDIT: I have solved my problem. All I needed was to change the send and third ifs to if elses. If anyone could tell me why this is, I'd love to know.

I've made a simple pong game, using Rectangle.Intersects(Rectangle) for hit detection. However, I'd like some more variability, so I want the ball to move differently depending on the spot on the paddle it was hit. [Ball movement has an XSpeed value and a YSpeed value, and each Update the ball moves along the X-axis a number of pixels equal to XSpeed; ditto for Y-axis and YSpeed.]

This is what is intended:
If the ball hits the top third of the paddle, YSpeed decreases by 1. If the ball hits the middle third of the paddle, YSpeed doesn't change. If the ball hits the bottom third of the paddle, YSpeed increases by 1. If the ball hits any part of the paddle, the XSpeed is reversed.

However, since I subdivided the paddles into three Rectangles, hit detection no longer functions properly. The ball changes direction only if the middle third of the paddle is hit, and the ball just flies through the top and bottom thirds.

This is really weird. I can not find the error. I've gone over the code several times, but I'm just stuck.


[source lang="csharp"]private void checkHit()
{
Rectangle paddle1RectTop = new Rectangle(paddle1.X, paddle1.Y, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle1RectMid = new Rectangle(paddle1.X, paddle1.Y + paddleTexture.Height / 3, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle1RectBot = new Rectangle(paddle1.X, paddle1.Y + paddleTexture.Height * (2/3), paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle2RectTop = new Rectangle(paddle2.X, paddle2.Y, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle2RectMid = new Rectangle(paddle2.X, paddle2.Y + paddleTexture.Height / 3, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle2RectBot = new Rectangle(paddle2.X, paddle2.Y + paddleTexture.Height * (2/3), paddleTexture.Width, paddleTexture.Height / 3);
Rectangle ballRect = new Rectangle(ball.X, ball.Y, ballTexture.Width, ballTexture.Height);

Boolean hasHitPaddle1Top = paddle1RectTop.Intersects(ballRect);
Boolean hasHitPaddle1Mid = paddle1RectMid.Intersects(ballRect);
Boolean hasHitPaddle1Bot = paddle1RectBot.Intersects(ballRect);
Boolean hasHitPaddle2Top = paddle2RectTop.Intersects(ballRect);
Boolean hasHitPaddle2Mid = paddle2RectMid.Intersects(ballRect);
Boolean hasHitPaddle2Bot = paddle2RectBot.Intersects(ballRect);

if(hasHitPaddle1Top || hasHitPaddle2Top)
{
ball.XSpeed = -ball.XSpeed;
ball.YSpeed = ball.YSpeed - 1;
}
if(hasHitPaddle1Mid || hasHitPaddle2Mid)
{
ball.XSpeed = -ball.XSpeed;
}
if(hasHitPaddle1Bot || hasHitPaddle2Bot)
{
ball.XSpeed = -ball.XSpeed;
ball.YSpeed = ball.YSpeed + 1;
}
}[/source]
Advertisement

EDIT: I have solved my problem. All I needed was to change the send and third ifs to if elses. If anyone could tell me why this is, I'd love to know.


A possible explanation (hard to say without testing it out myself) but with the three statements as individual if statements it would execute more than one. This could mean at times you were essentially reversing direction more than once and making it appear as if you didn't change direction.
What Pyrodrgn described happened to me in my first try at pong. Now, everything is object oriented, which makes bugfixes easier. Why don't you make a paddle class to hold the floatrects and pass them in to a function in your ball class to test collision?

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

You don't need 3 Rectangles on 1 paddle to calculate the movement of the ball.

- The ball has a velocity(X,Y) and a position(X,Y) as type: double or float. Each update you do m_Position += m_Velocity; So the ball moves depending on his velocity.
- Create 1 Hitregion(Rectangle) for 1 paddle
- When the hitregion of the paddle and the ball return true...
- Calculate a vector from the center of the paddle and the center of the ball.
- Merge that vector and the velocity of the ball.
- (This depends on how the vector is calculated) you might need to reverse the X-value of the new velocity so the ball goes the other way.

The new velocity will be added to the position of the ball. So if the ball hits the top of the paddle the Y-value will be less than if the ball hits the bottom of the paddle.
Have I explained the idea decently? smile.png

Note: m_Velocity is a vector. Have a look in a book how vectors are calculated! m_Position is a Point, which has an operator += that add the velocity to the position.


Also. Try to avoid allocating and deallocating objects at run-time. Create the paddles and their hit-regions at compile-time. smile.png
By the way are you having memory leaks? You are allocating Rectangles but aren't deallocating them in that function..... That function is called in a while-loop right? If so, you need to delete the Rectangles at the end of the function.


~EngineProgrammer

EDIT: I have solved my problem. All I needed was to change the send and third ifs to if elses. If anyone could tell me why this is, I'd love to know.


Let's have a look at your code:
[rollup='Source Code']
[source lang="csharp"]
private void checkHit()
{
Rectangle paddle1RectTop = new Rectangle(paddle1.X, paddle1.Y, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle1RectMid = new Rectangle(paddle1.X, paddle1.Y + paddleTexture.Height / 3, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle1RectBot = new Rectangle(paddle1.X, paddle1.Y + paddleTexture.Height * (2/3), paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle2RectTop = new Rectangle(paddle2.X, paddle2.Y, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle2RectMid = new Rectangle(paddle2.X, paddle2.Y + paddleTexture.Height / 3, paddleTexture.Width, paddleTexture.Height / 3);
Rectangle paddle2RectBot = new Rectangle(paddle2.X, paddle2.Y + paddleTexture.Height * (2/3), paddleTexture.Width, paddleTexture.Height / 3);
Rectangle ballRect = new Rectangle(ball.X, ball.Y, ballTexture.Width, ballTexture.Height);

Boolean hasHitPaddle1Top = paddle1RectTop.Intersects(ballRect);
Boolean hasHitPaddle1Mid = paddle1RectMid.Intersects(ballRect);
Boolean hasHitPaddle1Bot = paddle1RectBot.Intersects(ballRect);
Boolean hasHitPaddle2Top = paddle2RectTop.Intersects(ballRect);
Boolean hasHitPaddle2Mid = paddle2RectMid.Intersects(ballRect);
Boolean hasHitPaddle2Bot = paddle2RectBot.Intersects(ballRect);

if(hasHitPaddle1Top || hasHitPaddle2Top)
{
ball.XSpeed = -ball.XSpeed;
ball.YSpeed = ball.YSpeed - 1;
}
if(hasHitPaddle1Mid || hasHitPaddle2Mid)
{
ball.XSpeed = -ball.XSpeed;
}
if(hasHitPaddle1Bot || hasHitPaddle2Bot)
{
ball.XSpeed = -ball.XSpeed;
ball.YSpeed = ball.YSpeed + 1;
}
[/source]
[/rollup]

What happens when the ball hits BOTH the top and middle paddle rectangles? Walking through your code, it will:

  1. invert the ball.XSpeed and adjust the Ball.YSpeed by -1 (from within the first IF statement); and
  2. revert the ball.XSpeed (from within the second IF statement).

Having performed all appropriate updates the function ends and the ball is updated yet again (in the next update cycle). Depending on the speed of the ball, this next update may very well move its position BEYOND the paddle (because the second applied IF statement reverted the x-direction). Or it may continue in the same manner - applying two of the if statements (which cancel themselves out).
You could have (conversely) only allowed one 'hasHitPaddle' flags to be set to true (and discontinued testing for any others). This would have ensured that only one IF statement was processed (much the same as your use of ElseIf has done).

-Shadow

Also. Try to avoid allocating and deallocating objects at run-time. Create the paddles and their hit-regions at compile-time. smile.png
By the way are you having memory leaks? You are allocating Rectangles but aren't deallocating them in that function..... That function is called in a while-loop right? If so, you need to delete the Rectangles at the end of the function.


~EngineProgrammer


I think you may be confused on what language he is using. He is using C#.and not C++. That stuff is left up to the garbage collector.

[quote name='EngineProgrammer' timestamp='1348926458' post='4985043']
Also. Try to avoid allocating and deallocating objects at run-time. Create the paddles and their hit-regions at compile-time. smile.png
By the way are you having memory leaks? You are allocating Rectangles but aren't deallocating them in that function..... That function is called in a while-loop right? If so, you need to delete the Rectangles at the end of the function.


~EngineProgrammer


I think you may be confused on what language he is using. He is using C#.and not C++. That stuff is left up to the garbage collector.
[/quote]

Yes - deallocation of memory is left to the garbage collector. Still yet - the programmer is creating a seven new rectangles during each update cycle. I believe EngineProgrammer was only trying to say that the rectangles should be created only once. From that point forward, the only values that should change are the X & Y values. The paddle (in the original pong) doesn't change sizes so the width and height values will remain constant.

Is it completely necessary - probably not. Pong isn't so memory intensive that the creating the 7 rectangles 60 times a second will be noticed. But isn't it better to break bad programming habits earlier on? It'd probably clean up the code a bit too...

-Shadow
Thanks a bunch for the help, guys! Looking at it now, yes, the Rectangles should be created only once. That wasn't a very good idea on my part. As for you suggestion, EngineProgrammer:


- The ball has a velocity(X,Y) and a position(X,Y) as type: double or float. Each update you do m_Position += m_Velocity; So the ball moves depending on his velocity.
- Create 1 Hitregion(Rectangle) for 1 paddle
- When the hitregion of the paddle and the ball return true...
- Calculate a vector from the center of the paddle and the center of the ball.
- Merge that vector and the velocity of the ball.
- (This depends on how the vector is calculated) you might need to reverse the X-value of the new velocity so the ball goes the other way.


... I don't know what a vector is. (I know what a vector in physics is, but I don't know anything about them in gaming/programming terms.) I'll go look it up and try out your suggestion! However, what do you mean "merge the vectors?" Is merging something I'll learn about when looking up vectors?

Also, in response to Pyrodrgn, I do have a Paddle class and a Ball class. I'm still getting used to making my own objects like this, and I'm still not very good at deciding what each class should be in charge of.
Actually I was thinking he was programming in C++.. biggrin.png
I don't see a single tag it was C# so sorry for the misunderstanding!
And yes I also meant too much rectangles are created. There are only 2 paddles so there should be only 2 Rectangles. And 1 ball so 1 Circle(Or Ellipse, don't know what typedef you use in C#)

JDCAce, sorry for the non-mathematics terms, it was late so didn't really want to think on those English words ^^ (My native is not English)
I meant an addition of vectors. The ball has a velocity(represented as vector).

Example:
the ball has a position: X 24 Y 28 and a velocity of X -1 Y 2
Each time a gamecycle has past you need to add the velocity to the position. So next game cycle the ball has moved left/down and his position will be X 23 Y 30.
When the ball hits a paddle you calculate a new vector(with the angle the paddle and the ball has hit), you make a sum with that new vector and the velocity.

Here is a link, write down how a vector works in mathematics and try for your own to change it to computer language. It's very good practice.: http://programmedles...00/vch00_1.html
You will see in the future you will need mathematics now and then so I suggest you to buy a book. smile.png


~EngineProgrammer
Maybe I can give you some pseudo code of how I should write a pong game.


struct Position; // will store 2 integers
struct Velocity; // will store 2 integers, you can also add a gravity if you want to make the pong game more challenging

int main() {

Ball ball(Position, Velocity);
Paddle leftPaddle(Position);
Paddle rightPaddle(Position);

while(true) // I don't do this in a real pong game! pseudo code remember
{
ball.Update();
leftPaddle.Update(); // only update when player 1 has hit down or up.
rightPaddle.Update();

ball.CollisionDetection(leftPaddle); // when they collide, new velocity will be calculated.
ball.CollisionDetection(rightPaddle);

if(ball.OutOfGame())
if(ball.Position < 0) Player 2 has made a point.
else Player 1 has made a point.
restart game after a few gamecycles.

ball.Draw();
leftPaddle.Draw();
rightPaddle.Draw();
}

This topic is closed to new replies.

Advertisement