How to make simple A.I and collision in a pong clone

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Biphe
Prole
Posts: 13
Joined: Sun Jun 17, 2012 1:38 am

How to make simple A.I and collision in a pong clone

Post 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! ^-^
Attachments
main.love
(413 Bytes) Downloaded 148 times
User avatar
mcjohnalds45
Prole
Posts: 18
Joined: Sat Jun 02, 2012 12:08 pm

Re: How to make simple A.I and collision in a pong clone

Post 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.
Biphe
Prole
Posts: 13
Joined: Sun Jun 17, 2012 1:38 am

Re: How to make simple A.I and collision in a pong clone

Post by Biphe »

Thank you I never thought of that.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest