2d collision - sphere<->line
Rem Project: Dark Basic Pro Project
Rem Created: Wednesday, August 11, 2010
Rem ***** Main Source File *****
type vec2
x as float
y as float
endtype
type lin
P1 as vec2
P2 as vec2
endtype
dim lines(-1) as lin
for n=0 to 20
array insert at bottom lines()
index=array count(lines())
lines(index).P1.x=rnd(screen width())
lines(index).P2.x=rnd(screen width())
lines(index).P1.y=rnd(screen height())
lines(index).P2.y=rnd(screen height())
next
circ as vec2
r as float
ang as float
r=10.0
do
cls
if mouseclick()
circ.x=mousex()
circ.y=mousey()
endif
if upkey()
inc circ.x,cos(ang)
inc circ.y,sin(ang)
endif
if leftkey() then dec ang,1
if rightkey() then inc ang,1
circle circ.x,circ.y,r
circle circ.x+cos(ang)*r,circ.y+sin(ang)*r,2
for n=0 to array count(lines())
P1 as vec2
P2 as vec2
P1=lines(n).P1
P2=lines(n).P2
linColl(P1,P2,circ,r)
line p1.x,p1.y,p2.x,p2.y
circ=retvec
next
sync
loop
function linColl(P1 as vec2, P2 as vec2, C as vec2, r as float)
global retvec as vec2
retvec=C
local v3 as vec2
local v4 as vec2
local v10 as vec2
local delt as vec2
local d as float
v4.x=P2.x-C.x ```y4=P2-c : y3=P1-c
v4.y=P2.y-C.y
v3.x=P1.x-C.x
v3.y=P1.y-C.y
v10.x=v4.x-v3.x
v10.y=v4.y-v3.y
delt.x=v10.y*(v3.x*v10.y-v3.y*v10.x)/(v10.y*v10.y+v10.x*v10.x)
if v10.y=0
delt.y=P1.y-C.y
else
delt.y=-v10.x*delt.x/v10.y
endif
d=delt.x*delt.x+delt.y*delt.y
if v10.x=0
t#=(delt.y-v3.y)/v10.y
else
t#=(delt.x-v3.x)/v10.x
endif
if d<=r*r and t#>0 and t#<1
d=sqrt(d)
`circle circlex,circley,radius
local x as vec2
x.x=delt.x/d
x.y=delt.y/d
pointColl(C,x,r,d)
else
local x as vec2
x.x=P1.x-C.x
x.y=P1.y-C.y
d=sqrt(x.x*x.x+x.y*x.y)
x.x=x.x/d
x.y=x.y/d
if pointColl(C,x,r,d)
else
local x as vec2
x.x=P1.x-C.x
x.y=P1.y-C.y
d=sqrt(x.x*x.x+x.y*x.y)
x.x=x.x/d
x.y=x.y/d
pointColl(C,x,r,d)
endif
endif
endfunction
function pointColl(C as vec2, x as vec2, r as float, d as float)
global retvec as vec2
retvec=C
if d<r
retvec.x=C.x-(r-d)*x.x
retvec.y=C.y-(r-d)*x.y
exitfunction 1
endif
endfunction 0
The program I wrote figures out the point of intersection during the process, so once you get the point of intersection, you can just do point collision response, which is basically this (where C is the center of the circle, P is the point you're colliding with, d is the distance between the two points, x with ^ over it is the direction from C to P, and r is the radius of the circle):
so its actually prty simple once the point of intersection is figured out.