Jump to content

  • Log In with Google      Sign In   
  • Create Account

Pong Hit Detection


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
13 replies to this topic

#1 JDCAce   Members   -  Reputation: 146

Like
1Likes
Like

Posted 28 September 2012 - 10:26 PM

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]

Edited by Josh Petrie, 30 September 2012 - 10:11 PM.


Sponsor:

#2 PyroDragn   Members   -  Reputation: 404

Like
1Likes
Like

Posted 29 September 2012 - 05:50 AM

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.

#3 superman3275   Crossbones+   -  Reputation: 2011

Like
0Likes
Like

Posted 29 September 2012 - 07:09 AM

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?

Edited by superman3275, 29 September 2012 - 07:11 AM.

I'm a game programmer and computer science ninja ph34r.png!

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 smile.png!


#4 EngineProgrammer   Members   -  Reputation: 295

Like
3Likes
Like

Posted 29 September 2012 - 07:47 AM

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? Posted Image

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. Posted Image
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

#5 ShadowValence   Members   -  Reputation: 380

Like
0Likes
Like

Posted 29 September 2012 - 10:11 AM

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:
Source Code


What happens when the ball hits BOTH the top and middle paddle rectangles? Walking through your code, it will:
  • invert the ball.XSpeed and adjust the Ball.YSpeed by -1 (from within the first IF statement); and
  • 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

#6 Chad Smith   Members   -  Reputation: 1134

Like
0Likes
Like

Posted 29 September 2012 - 05:57 PM

Also. Try to avoid allocating and deallocating objects at run-time. Create the paddles and their hit-regions at compile-time. Posted Image
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.

#7 ShadowValence   Members   -  Reputation: 380

Like
0Likes
Like

Posted 29 September 2012 - 06:26 PM


Also. Try to avoid allocating and deallocating objects at run-time. Create the paddles and their hit-regions at compile-time. Posted Image
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.


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

#8 JDCAce   Members   -  Reputation: 146

Like
0Likes
Like

Posted 29 September 2012 - 06:59 PM

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.

Edited by JDCAce, 29 September 2012 - 08:12 PM.


#9 EngineProgrammer   Members   -  Reputation: 295

Like
1Likes
Like

Posted 30 September 2012 - 10:12 AM

Actually I was thinking he was programming in C++.. Posted Image
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. Posted Image


~EngineProgrammer

#10 EngineProgrammer   Members   -  Reputation: 295

Like
0Likes
Like

Posted 30 September 2012 - 10:23 AM

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();	
}


#11 JDCAce   Members   -  Reputation: 146

Like
0Likes
Like

Posted 30 September 2012 - 08:00 PM

Thank you very much, EngineProgrammer! I think this will still be tough, but you've given me a great head start!

UPDATE: It works! Using some math I found elsewhere, I got my program to run flawlessly! Now for my next project: Randomly-dropped power-ups!

Edited by JDCAce, 30 September 2012 - 10:07 PM.


#12 Chad Smith   Members   -  Reputation: 1134

Like
0Likes
Like

Posted 01 October 2012 - 01:27 AM



Also. Try to avoid allocating and deallocating objects at run-time. Create the paddles and their hit-regions at compile-time. Posted Image
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.


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


Yes that may be true but I was talking more towards when he said it looked like he had a memory leak because he was not deleting what he would new. That is why I just wanted to bring up that he was using C# and not C++. Sorry for the misunderstanding.

#13 ShadowValence   Members   -  Reputation: 380

Like
0Likes
Like

Posted 01 October 2012 - 01:20 PM

Yes that may be true but I was talking more towards when he said it looked like he had a memory leak because he was not deleting what he would new. That is why I just wanted to bring up that he was using C# and not C++. Sorry for the misunderstanding.


Oh - my bad. :D

BTW - I wasted a little time yesterday and on my machine, I didn't really see any performance hits until well above the 1000 rectangles mark. I had a < .00005 loss when recreating the 1000 rectangles. At 10'000 rectangles, adjusting the X & Y values of the rectangle ran around .0005 seconds (.5 ms) per frame while creating new ones each cycle dropped me to .0009 seconds (.9ms) per frame. Inversely - that's a drop from ~2000FPS to ~1100FPS.

Again - not really a necessity for something so simple as rectangles. But an interesting experiment and good learning experience none-the-less!

#14 JDCAce   Members   -  Reputation: 146

Like
0Likes
Like

Posted 01 October 2012 - 02:49 PM

I agree, ShadowValence. I worked on my coding and I think it's a lot cleaner and a bit more efficient now. Like I said, I found the math elsewhere, so I won't claim that as mine, but after a lot of working, I think I understand it. Also, as EngineProgrammer suggested, I made only one Rectangle per paddle (and one per ball), and saved the values in the respective class (ie, leftPaddle.rectangle). I added an Update() method to the Paddle class in which the values of the rectangle are updated, using rectangle.X and rectangle.Y, instead of creating a whole new rectangle each Update().

This project really has turned out to be a valuable learning experience, and I can't thank all of you enough!

Code





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS