Here is a generalization to n-degree curves, which allows more complex curves.
Just for the interested.
Code: Select all
' Testprogram for bezier curve function
' a n-degree bezier curve has n+1 control points: 2 end points and
' n-1 "handles" that control the shape of the curve.
' To try different degrees: modify the variable "degree" and modify
' the READ DATA construct accordingly.
' Bezier curves can easily be rotated, scaled, and translated. See
' Ricardobyte's thread "Poly Designer" for more on this.
'
' Move the control points slowly in order to keep tracking
'
option angle degrees ! option base 0
graphics ! graphics clear ! refresh off
draw color 0,0,0
degree=4
np=degree+1
dim cp(np,2)
for i=0 to degree ! READ cp(i,0),cp(i,1) ! next i
DATA 100,200, 350,50, 200,200, 550,370, 150,300
goto go_on
loop: get touch 0 as x,y
if x=-1 then loop
for i=0 to degree
if (x-cp(i,0))^2 + (y-cp(i,1))^2 < 300 then
cp(i,0)=x ! cp(i,1)=y ! goto go_on
end if
next i
go_on: graphics clear
bezier(degree,cp,30,3)
goto loop
end
' draw n-degree bézier curve (option base 0) assumed)
' deg is the degree of the curve
' cp contains x and y of end points and handles
' cp(0) and cp(deg) are the endpoints, handles in between.
' steps is the number of line segments used to draw the curve
' pen is the line thickness
'
def bezier(deg,cp(,),steps,pen)
np=deg+1 ' calculate factorial table and "n over k" table
dim fac(np),nok(np),p(np,2)
fac(0)=1 ! for i=1 to deg ! fac(i)=i*fac(i-1) ! next i
for i=0 to deg ! nok(i)=fac(deg)/fac(deg-i)/fac(i) ! next i
for i=0 to deg ! p(i,0)=cp(i,0) ! p(i,1)=cp(i,1) ! next i
draw size 3 ! fill color 0,0,1 ' draw end points and handles
fill circle p(0,0),p(0,1) size 5
fill circle p(deg,0),p(deg,1) size 5
for i=1 to deg-1 ! draw circle p(i,0),p(i,1) size 5 ! next i
draw size 1 ! draw alpha .3
draw line p(0,0),p(0,1) to p(1,0),p(1,1)
draw line p(deg,0),p(deg,1) to p(deg-1,0),p(deg-1,1)
draw size pen ! draw alpha 1
' draw the curve
t=0 ! dt=1/steps ! draw size pen ! draw to p(0,0),p(0,1)
for i=1 to steps
t+=dt ! tm=1-t ! x=0 ! y=0 ! a=tm^deg ! b=1
for j=0 to deg
f=nok(j)*a*b ! x+=f*p(j,0) ! y+=f*p(j,1)
a/=tm ! b*=t
next j
draw line to x,y
next i
refresh
end def