Collision Circle/Square or Rectangle with Pico8
Sometimes I do useless stuff just for fun and to get my brain fired up, when simpler solutions exist!!! If you had to choose only one solution, the second one is the most reasonable ;-)
#pixcode 2: There is a collision, but D > 0, so the collision is not detected. We need to check the vertical and horizontal alignment.
 function _init()
--circle center
x1=90
y1=60
--square center
x2=60
y2=80
d=10 --square side/2
r=10 --radius
end
function _update()
--controls 
if (btn(0)) x1-=1
if (btn(1)) x1+=1
if (btn(2)) y1-=1
if (btn(3)) y1+=1
--calculate oc
a=abs(x1-x2)
b=abs(y1-y2)
oc=sqrt(a^2+b^2)
--calculate sine and cosine
cosa=b/oc
sina=a/oc 
--calculate di. The value 0.7071 is only for a square 
if cosa <= 0.7071 then 
    di=d/sina
else di=d/cosa
end
--check collision with a corner or middle edge
if (oc<=(r+di)) then
    corner=1
else corner=0
end
--check the collision with edges
if a<=d and b<=(r+d) then
    touchh=1
else touchh=0 
end
if b<=d and a<=(r+d) then
    touchv=1
else touchv=0
end
--calculate Deltad (not necessary)
deltad=oc-(r+di)
end--end update
function _draw()
cls()
--draw points
pset(x1,y1,8) --circle center
pset(x2,y2,10) --square center
--circle
circ(x1,y1,r,8)
--square
rect((x2-d),(y2-d),(x2+d),(y2+d),10)
--collision detection
if  corner==1 or (touchh==1 or touchv==1) then
    rectfill((x2-d),(y2-d),(x2+d),(y2+d),8)
end
--line circle center to square center
line(x1,y1,x2,y2,14)
end
 
2- Collision circle/rectangle or square (easy!)
This method is the easiest ->
pico-8 cartridge // http://www.pico-8.com
version 30
__lua__
function _init()
--circle center and radius
x1=90
y1=60
r=10
--rectangle center, width and height. For a square w=h
x2=60
y2=80
w=40
h=20
end--
function _update()
--controls 
if (btn(0)) x1-=1
if (btn(1)) x1+=1
if (btn(2)) y1-=1
if (btn(3)) y1+=1
--calculate dh,dv,
dh=abs(x1-x2)
dv=abs(y1-y2)
distx=(dh-(w/2)) --dx
disty=(dv-(h/2)) --dy
distr=distx^2+disty^2 --d
--check collision with corners
if distr<=r^2 then
    collision=1
else collision=0
end
--check the collision with horizontal edges
if dh<=(w/2) and dv<=(r+(h/2)) then
    touchh=1
else touchh=0 
end
--check the collision with vertical edges
if dv<=(h/2) and dh<=(r+(w/2)) then
    touchv=1
else touchv=0
end
end
function _draw()
cls()
--draw points
pset(x1,y1,8) --circle center
pset(x2,y2,10) --square center
--circle
circ(x1,y1,r,8)
--square
rect((x2-(w/2)),(y2-(h/2)),(x2+(w/2)),(y2+(h/2)),10)
--collision detection
if  collision==1 or (touchh==1 or touchv==1) then
    rectfill((x2-(w/2)),(y2-(h/2)),(x2+(w/2)),(y2+(h/2)),8)
end
--line circle center to square center
line(x1,y1,x2,y2,14)
end



Commentaires
Enregistrer un commentaire