Last active
October 17, 2017 16:51
-
-
Save josefnpat/4044150 to your computer and use it in GitHub Desktop.
LÖVE: Line and Circle Collision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
circle = {x=400,y=300,r=100} | |
point = { x = 100, y = 100 } | |
col = false | |
function love.draw() | |
if cols then | |
love.graphics.print("Collision",0,0) | |
love.graphics.setColor(255,0,0) | |
for _,col in pairs(cols) do | |
love.graphics.circle("line",col.x,col.y,5) | |
end | |
else | |
love.graphics.setColor(255,255,255) | |
end | |
love.graphics.circle("line",circle.x,circle.y,circle.r) | |
love.graphics.line(mx,my,point.x,point.y) | |
love.graphics.line(circle.x,circle.y,point.x,point.y) | |
end | |
function love.update(dt) | |
mx,my = love.mouse.getPosition() | |
mx,my = mx,my | |
cols = collision_line_and_circle(point,{x=mx,y=my},circle) | |
end | |
function love.mousepressed(x,y,button) | |
if button == "l" then | |
point.x = x | |
point.y = y | |
elseif button == "r" then | |
circle.x = x | |
circle.y = y | |
elseif button == "wd" then | |
circle.r = circle.r+10 | |
elseif button == "wu" then | |
circle.r = circle.r-10 | |
end | |
end | |
function collision_line_and_circle(point1,point2,circle) | |
local v1 = vector.new(point1,point2) | |
local v2 = vector.new(point1,circle) | |
local v1_mag = vector.mag(v1) | |
local v2_mag = vector.mag(v2) | |
local alpha = math.acos( vector.dot(v1,v2) / ( v1_mag * v2_mag ) ) | |
local dist_o = math.sin(alpha) * v2_mag | |
if dist_o <= circle.r then | |
local mag_a_r_left = dist_o / math.tan(alpha) | |
local mag_a_r_right = circle.r * math.sin( math.acos( dist_o / circle.r ) ) | |
local mag_a_r_close = mag_a_r_left - mag_a_r_right | |
local mag_a_r_far = mag_a_r_left + mag_a_r_right | |
return { | |
{ | |
x = point1.x - v1.x / v1_mag * mag_a_r_close, | |
y = point1.y - v1.y / v1_mag * mag_a_r_close, | |
}, | |
{ | |
x = point1.x - v1.x / v1_mag * mag_a_r_far, | |
y = point1.y - v1.y / v1_mag * mag_a_r_far, | |
}, | |
} | |
end | |
end | |
function distance(point1,point2) | |
return math.sqrt((point1.x - point2.x)^2 + (point1.y - point2.y)^2) | |
end | |
vector = {} | |
function vector.dot(vector1,vector2) | |
return vector1.x*vector2.x + vector1.y*vector2.y | |
end | |
function vector.mag(vector) | |
return math.sqrt(vector.x^2 + vector.y^2) | |
end | |
function vector.new(point1,point2) | |
local v = {} | |
v.x = point1.x - point2.x | |
v.y = point1.y - point2.y | |
return v | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment