Skip to content

Instantly share code, notes, and snippets.

@jcollard
Created May 9, 2024 20:05
Show Gist options
  • Save jcollard/4bc03250288183048db5e8934b32fb0e to your computer and use it in GitHub Desktop.
Save jcollard/4bc03250288183048db5e8934b32fb0e to your computer and use it in GitHub Desktop.
-- Collision Detection Challenge
function RandomizeWall()
Wall.x = math.random(0, 200)
Wall.y = math.random(24, 100)
Wall.width = math.random(8, 100)
Wall.height = math.random(8, 100)
end
function IsColliding()
-- If the player's left is
-- to the right of the wall, it is
-- not colliding (return false)
local wallRight = Wall.x + Wall.width
local playerLeft = Player.x
if playerLeft >= wallRight then
return false
end
-- TO DO: There are 3 more conditions
-- to finish collision detection.
-- What are they?
-- playerRight < wallLeft
local playerRight = Player.x + Player.width
local wallLeft = Wall.x
if playerRight < wallLeft then
return false
end
-- If player bottom < wall top
local playerBottom = Player.y + Player.height
local wallTop = Wall.y
if playerBottom < wallTop then
return false
end
local playerTop = Player.y
local wallBottom = Wall.y + Wall.height
if playerTop > wallBottom then
return false
end
return true
end
-- You do not need to edit anything below this line
function BOOT()
Player = CreateActor(200, 80, 10, 10, 1)
Wall = CreateActor(112, 36, 8, 82, 2)
end
function CreateActor(x, y, w, h, c)
local newWall = {}
newWall.x = x
newWall.y = y
newWall.width = w
newWall.height = h
newWall.color = c
return newWall
end
function TIC()
Input()
Update()
Draw()
end
function Input()
MoveInput()
end
function MoveInput()
if btn(0) then Player.y = Player.y - 1 end
if btn(1) then Player.y = Player.y + 1 end
if btn(2) then Player.x = Player.x - 1 end
if btn(3) then Player.x = Player.x + 1 end
if btnp(4) then RandomizeWall() end
end
function Update()
if IsColliding() then
Player.color = 12
else
Player.color = 1
end
end
function Draw()
cls(0)
DrawActor(Wall)
DrawActor(Player)
DrawInfo()
end
function DrawActor(a)
rect(a.x, a.y, a.width, a.height, a.color)
end
function DrawInfo()
print("Press 'A' to RandomizeWall", 0, 0, 12)
print("Player Bounds: (" .. Player.x .. ", " .. Player.y .. ") - (" .. Player.x + Player.width .. ", " .. Player.y + Player.height .. ")", 0, 8, 12)
print("Wall Bounds: (" .. Wall.x .. ", " .. Wall.y .. ") - (" .. Wall.x + Wall.width .. ", " .. Wall.y + Wall.height .. ")", 0, 16, 12)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment