
-----------------------------------
poll262
Mon Jun 18, 2012 5:27 pm

Air Hockey collision problem
-----------------------------------
I am making an air hockey game and am having difficulties getting the puck to bounce off of the paddle in the right direction. Plus sometimes the puck will get stuck inside of the paddle. Here is my code so far.


View.Set ("graphics:1000;600, offscreenonly")
var paddleX, paddleY, paddleRadius, button : int
var ballX, ballY, ballRadius, vx, vy : int

ballX := 500
ballY := 300
paddleRadius := 20
ballRadius := 20
vx := (Rand.Int (0, 1) * 2) - 1
vy := (Rand.Int (0, 1) * 2) - 1

procedure graphics

    drawarc (0, 300, 90, 90, 270, 90, red)
    drawarc (1000, 300, 90, 90, 90, 270, red)
    drawfillbox (490, 0, 510, 600, red)
    drawfillbox (250, 0, 255, 600, blue)
    drawfillbox (750, 0, 755, 600, blue)
    drawfilloval (paddleX, paddleY, paddleRadius, paddleRadius, blue)
    drawfilloval (ballX, ballY, ballRadius, ballRadius, black)

end graphics

procedure ballMove

    ballX := ballX - vx
    ballY := ballY - vy

    if Math.Distance (paddleX, paddleY, ballX, ballY) < paddleRadius * 2 then
        vx := -vx
        vy := -vy
    end if

    if ballX + ballRadius >= maxx then
        vx := -vx
    elsif ballX - ballRadius = maxy then
        vy := -vy
    elsif ballY - ballRadius  Plus sometimes the puck will get stuck inside of the paddle. 

That's because you move your position before checking if being in that position collides with something.

> bounce off of the paddle in the right direction.

What's happening is that, no matter the angle the two objects collide at, the puck will inverse it's direction. This is similar to shooting at a wall at any weird angle, and the bullet rebounding right back at you.

To quote http://upload.wikimedia.org/wikipedia/commons/2/2c/Elastischer_sto%C3%9F_2D.gif

This shows the process a bit. We're bouncing off the line perpendicular to the vector from one center of a circle to the next.

As for the math of what you need to do... Well, I'll leave that to someone who's actually done that before.

-----------------------------------
Raknarg
Mon Jun 18, 2012 7:25 pm

RE:Air Hockey collision problem
-----------------------------------
That doesnt seem right to me. What your'e saying is that at any given angle, they will reflect perpendicularly? That's wrong.

-----------------------------------
poll262
Mon Jun 18, 2012 7:34 pm

Re: Air Hockey collision problem
-----------------------------------
Also how can I use two different radius's to for the puck and the paddle. Whenever I use different radius's, Math.Distance will no longer work to detect when they are touching.

-----------------------------------
Raknarg
Mon Jun 18, 2012 7:47 pm

RE:Air Hockey collision problem
-----------------------------------
if Math.Distance (x1, y1, x2, y2) 