• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
JDCAce

Pong Hit Detection

13 posts in this topic

[b]EDIT:[/b] I have solved my problem. All I needed was to change the send and third [b]if[/b]s to [b]if else[/b]s. If anyone could tell me [i]why[/i] 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. [i][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.][/i]

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
1

Share this post


Link to post
Share on other sites
[quote name='JDCAce' timestamp='1348892806' post='4984958']
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.
[/quote]

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.
1

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
[quote name='JDCAce' timestamp='1348892806' post='4984958']
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.
[/quote]

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:[list=1]
[*]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).
[/list]
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
0

Share this post


Link to post
Share on other sites
[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. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
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
[/quote]

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.
0

Share this post


Link to post
Share on other sites
[quote name='Chad Smith' timestamp='1348963079' post='4985195']
[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. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
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
[/quote]

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
0

Share this post


Link to post
Share on other sites
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:

[quote name='EngineProgrammer' timestamp='1348926458' post='4985043']
- 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.
[/quote]

... 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
0

Share this post


Link to post
Share on other sites
Actually I was thinking he was programming in C++.. [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]
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.: [url="http://programmedlessons.org/VectorLessons/vch00/vch00_1.html"]http://programmedles...00/vch00_1.html[/url]
You will see in the future you will need mathematics now and then so I suggest you to buy a book. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]


~EngineProgrammer
1

Share this post


Link to post
Share on other sites
Maybe I can give you some pseudo code of how I should write a pong game.

[CODE]
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();
}
[/CODE]
0

Share this post


Link to post
Share on other sites
Thank you very much, EngineProgrammer! I think this will still be tough, but you've given me a great head start!

[b]UPDATE:[/b] 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
0

Share this post


Link to post
Share on other sites
[quote name='ShadowValence' timestamp='1348964788' post='4985200']
[quote name='Chad Smith' timestamp='1348963079' post='4985195']
[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. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
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
[/quote]

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
[/quote]

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.
0

Share this post


Link to post
Share on other sites
[quote name='Chad Smith' timestamp='1349076449' post='4985667']
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.
[/quote]

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!
0

Share this post


Link to post
Share on other sites
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!

[rollup='Code'][CODE]
private void checkHit()
{
float intersectY = ball.location.Y;
float relativeIntersectY;
float normalizedRelativeIntersectY;
double bounceAngle;
if(leftPaddle.rectangle.Intersects(ball.rectangle))
{
relativeIntersectY = (leftPaddle.location.Y + (leftPaddle.Height / 2)) - intersectY;
normalizedRelativeIntersectY = (relativeIntersectY / (leftPaddle.Height / 2));
bounceAngle = (normalizedRelativeIntersectY * (Math.PI / 4));
ball.velocity.X = (float)(10 * Math.Cos(bounceAngle));
ball.velocity.Y = (float)(5 * -Math.Sin(bounceAngle));
}
else if(rightPaddle.rectangle.Intersects(ball.rectangle))
{
relativeIntersectY = (rightPaddle.location.Y + (rightPaddle.Height / 2)) - intersectY;
normalizedRelativeIntersectY = (relativeIntersectY / (rightPaddle.Height / 2));
bounceAngle = (normalizedRelativeIntersectY * (Math.PI / 4));
ball.velocity.X = (float)(10 * Math.Cos(bounceAngle));
ball.velocity.Y = (float)(5 * -Math.Sin(bounceAngle));
ball.velocity.X = -ball.velocity.X;
}
}
[/CODE]
[/rollup]
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0