Question

I am trying to work on a ping pong kind of game in jQuery and I was wondering how can I restrict the slider position inside a container.

I also need help with how to generate the ball/box and how to make it bounce on the side and top wall of the container.

I have managed to work on it but I am still struggling to retain the slider inside the container and struggling on the bouncing the ball around.

Any help would be highly appreciated. MyCodeSoFar

Was it helpful?

Solution

I'm sorry but your code is a bit messy for me. Whatever, I found this idea of a js pong like game funny and I adapted your code to do what you intended.

Just have a look at this fiddle and feel free to send me some feedback.

OTHER TIPS

You have asked a lot of general questions so I'll give you some general pointers. :)

I am trying to work on a ping pong kind of game in jQuery and I was wondering how can I restrict the slider position inside a container?

To constrain the paddle, just check some offsets.

To determine if it's touching the left border, check its offset from the left. If it's 0, ignore the keydown.

To determine if it's touching the right border, take the left offset and add the width of the paddle. If it's equal to the width of the game area, ignore the keydown.

I also need help with how to generate the ball/box and how to make it bounce on the side and top wall of the container.

Since you are using elements and not canvas, you can generate a ball with CSS...

#ball {
    width: 20px;
    height: 20px;
    border-radius: 20px;
}

The key here is the border-radius being equal to the width and height of the ball.

To get the ball to bounce, have a x and y velocity that is incremented with your game timer. Flip the sign of these when the ball collides with either the paddle or the edges of the game areas. To make it more Pong-like, you can mess with how you modify the bounce when it hits certain regions of the paddle, for example, if it hits the far edge, it has a sharper angle when it reverses.

To determine if the ball has hit the edge of the game area, use a technique similar to what I described above.

To determine if your ball has impacted your paddle, use some collision detection code. Check to see if the ball's Y offset is higher than the paddle's Y offset (I assume your paddle moves linearly on a horizontal track). Then, if that condition is met, see if the ball's X offset is within the range of the paddle's X offset and (+) the width of the paddle.

If your paddle and game area never change, it would be beneficial to cache these widths.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top