Collisions don't work right
Posted: Thu Jan 05, 2017 6:11 pm
Hello Guys! I have been trying to make a Pong clone. My progress stopped since the collisions on the top, bottom and paddles of the game didn't work. So it would be nice to help me out of this problem. And could you also suggest changes to improve me code?
Thanks.
Thanks.
Code: Select all
function love.load()
lplayer = {}
lplayer.x = 0
lplayer.y = love.graphics.getHeight() / 2
lplayer.len = 10
lplayer.height = 70
lplayer.pixels = 1200
rplayer = {}
rplayer.x = love.graphics.getWidth() - 10
rplayer.y = love.graphics.getHeight() / 2
rplayer.len = 10
rplayer.height = 70
rplayer.pixels = 1200
ball = {}
ball.x = love.graphics.getWidth() / 2
ball.y = love.graphics.getHeight() / 2
ball.len = 10
ball.height = 10
ball.dx = -300
ball.dy = 150
end
function love.update(dt)
-- INPUT FROM PLAYER 1 --
if (love.keyboard.isDown('d')) then
if ((lplayer.y + lplayer.height) < love.graphics.getHeight()) then
lplayer.y = lplayer.y + (lplayer.pixels * dt)
end
end
if (love.keyboard.isDown('a')) then
if (lplayer.y > 0) then
lplayer.y = lplayer.y - (lplayer.pixels * dt)
end
end
-- INPUT FROM PLAYER 2 --
if (love.keyboard.isDown('h')) then
if ((rplayer.y + rplayer.height) < love.graphics.getHeight()) then
rplayer.y = rplayer.y + (rplayer.pixels * dt)
end
end
if (love.keyboard.isDown('k')) then
if (rplayer.y > 0) then
rplayer.y = rplayer.y - (rplayer.pixels * dt)
end
end
-- UP and DOWN COLLISSION --
if (ball.y == 0) then
ball.dy = -ball.dy
elseif(ball.y == love.graphics.getHeight()) then
ball.dy = -ball.dy
end
-- BALL MOVEMENT --
ball.x = ball.x + (ball.dx * dt)
ball.y = ball.y + (ball.dy * dt)
-- BALL PADDLECOLISSION --
if (ball.x == lplayer.len and ball.y <= lplayer.y and ball.y >=(lplayer.y-lplayer.height)) then
ball.dx = -ball.dx
end
if (ball.x == (love.graphics.getWidth() - rplayer.len) and ball.y <= rplayer.y and ball.y >= (rplayer.y - rplayer.height)) then
ball.dx = -ball.dx
end
end
function love.draw()
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle("fill", lplayer.x, lplayer.y, lplayer.len, lplayer.height)
love.graphics.rectangle("fill", rplayer.x, rplayer.y, rplayer.len, rplayer.height)
love.graphics.rectangle("fill", ball.x, ball.y, ball.len, ball.height)
end