Page 1 of 1
How to make simple A.I and collision in a pong clone
Posted: Sun Jun 17, 2012 1:49 am
by Biphe
So I am trying to get the computer controlled pong player to follow the pong, also i am trying to get the pong to move, and I would like to know how to make a pong collision without using the complicated box2d physics engine.
The file is included below and thanks for your help! ^-^
Re: How to make simple A.I and collision in a pong clone
Posted: Sun Jun 17, 2012 4:06 am
by mcjohnalds45
First of all, to move the computer's paddle up and down, you can check if the pong is above the computers paddle and if it is move it up, then check if the pong is below the computers paddle and if it is move it down.
Code: Select all
if pong.y > computer.y + (computer.width / 2) then
computer.y = computer.y + (computer.speed * dt)
end
if pong.y < computer.y + (computer.width / 2) then
computer.y = computer.y - (computer.speed * dt)
end
-- the "+ (computer.width / 2)" is to check if the pong is above or below the centre of the paddle rather than the top
Getting the pong to move is a simple as two lines.
Code: Select all
pong.x = pong.x + (pong.speed * dt)
pong.y = pong.y + (pong.speed * dt)
Then to check if the pong is colliding width one of the paddles you can use this function that checks if the one rectangle is intersecting another.
Code: Select all
function collision(X1, Y1, W1, H1, X2, Y2, W2, H2)
if X1 > X2 + W2 then
return false
end
if X1 + W1 < X2 then
return false
end
if Y1 > Y2 + H2 then
return false
end
if Y1 + H1 < Y2 then
return false
end
return true
end
Example Usage.
Code: Select all
if collision(player.x, player.y, player.width, player.height, pong.x, pong.y, pong.size, pong.size) then
print("bazinga")
end
Finally i'd suggest making the ball move a little faster than the computer at some point or the computer will never lose.
Re: How to make simple A.I and collision in a pong clone
Posted: Sun Jun 17, 2012 7:35 am
by Biphe
Thank you I never thought of that.