practice/love/mike/lib/functions.lua

96 lines
2.3 KiB
Lua

function screen_col_detect(object, display)
if not (object.x >= -1 and
object.x <= (display.width - object.width)) then
return false
end
if not (object.y >= -1 and
object.y <= (display.height - object.height)) then
return false
end
return true
end
function create_object(start_x, start_y, width, height, speed)
local object = {}
object.x = start_x
object.y = start_y
object.width = width
object.height = height
object.speed = speed
return object
end
function num_is_pos(number)
if number > 0 then
return true
else return false
end
end
-- Inspired by https://love2d.org/wiki/BoundingBox.lua
-- Returns true if boxes overlap
function hitbox_collision(x1, y1, width1, height1,
x2, y2, width2, height2)
return x1 < x2 + width2 and
x2 < x1 + width1 and
y1 < y2 + height2 and
y2 < y1 + height1
end
-- Takes a string "left" or "right"
function bounce(str, ball)
if str == "right" and
not num_is_pos(ball.x_speed) then
ball.x_speed = ball.x_speed *-1
elseif
str == "left" and
num_is_pos(ball.x_speed) then
ball.x_speed = ball.x_speed *-1
end
return ball
end
function ball_bounce(player, ball, dt)
local paddle_hit = false
ball.x = ball.x + (ball.x_speed *dt)
ball.y = ball.y + (ball.y_speed *dt)
-- If ball hits screen wall
if ball.x >= screen.width or ball.x < 0 then
ball.x_speed = ball.x_speed * -1
end
-- If ball hits screen top
if ball.y >= screen.height then
ball.y_speed = ball.y_speed * -1
ball.score = ball.score + 1
end
-- If ball hits screen bottom
if ball.y <= 0 then
ball.y_speed = ball.y_speed * -1
end
-- If ball hits paddle
if hitbox_collision(ball.x, ball.y, ball.width, ball.height,
player.x, player.y, player.width, player.height) then
-- We don't need to check left limits because we already know
-- there was a collision, so just bounce left if the ball is
-- left of center on the paddle
if ball.x < player.x + (player.width /2) then
bounce("left", ball)
-- If the ball is on the right side, bounce right
elseif ball.x > player.x +(player.width /2) then
bounce("right", ball)
end
-- We don't really need to worry about the center
-- so we won't modify it.
-- Bounce
ball.y_speed = ball.y_speed *-1
end
return ball
end