Verlet Integration Please Help!

BlitzPlus Forums/BlitzPlus Programming/Verlet Integration Please Help!

Naughtical(Posted 2015) [#1]
I've been having problems implementing sticks. Run the code to see what I mean. It just flies off the screen!

;Verlet Integration
Const bounce#=0.7
Const gravity#=0.8
Const friction#= Float(1.003)
Const fps=12
width=1280
height=800
Graphics width,height,32,0

Type point
Field x
Field y
Field oldx
Field oldy
End Type

Type stick
Field pa
Field pb
Field length
End Type

world.point=New point
world\x=0
world\y=0
world\oldx=world\x-20
world\oldy=world\y-2

world.point=New point
world\x=0
world\y=0
world\oldx=world\x-22
world\oldy=world\y-5

stk.stick=New stick
stk\pa=0
stk\pb=1
length=Distance(stk\pa,stk\pb)

frames=CreateTimer(fps)
While Not KeyHit(1)
Cls
Gosub updatePoints
Gosub updateSticks
Gosub renderPoints
WaitTimer frames
Flip
Wend

;UPDATE POINTS
.updatePoints

For world.point= Each point
vx#= Float((world\x - world\oldx)/friction#)
vy#= Float((world\y - world\oldy)/friction#)

world\oldx = world\x
world\oldy = world\y
world\x = world\x+vx#
world\y = world\y+vy# + gravity

If world\x > width
world\x = width
world\oldx=world\x+vx#*bounce#
EndIf

If world\x < 0
world\x = 0
world\oldx=world\x+vx#*bounce#
EndIf

If world\y > height
world\y = height
world\oldy=world\y+vy#*bounce#
EndIf

If world\y < 0
world\y = 0
world\oldy=world\y+vy#*bounce#
EndIf

Next

Return

;UPDATE STICKS

.updateSticks
For stk.stick= Each stick

dx= GetPointX(stk\pa) - GetPointX(stk\pb)
dy= GetPointY(stk\pa) - GetPointY(stk\pb)
dist = Sqr(dx^2 + dy^2)
If dist = 0 Then dist = 1
diff = stk\length - dist
per = diff / dist / 2
offX = dx * per
offY = dy * per
SetPointX(stk\pa,GetPointX(stk\pa) - offX)
SetPointY(stk\pa,GetPointY(stk\pa) - offY)
SetPointX(stk\pb,GetPointX(stk\pb) + offX)
SetPointY(stk\pb,GetPointY(stk\pb) + offY)
Next

Return

.renderPoints
For world.point= Each point

Oval world\x-5,world\y-5,10,10,1

;Text 0,0,vx
;Text 0,20,vy

Next

Return

Function Distance(pa,pb)
pax=GetPointX(pa)
pay=GetPointY(pa)
pbx=GetPointX(pb)
pby=GetPointY(pb)
ret=Sqr(pa^2 * pb^2)
Return ret
End Function

Function GetPointX(pn)
world.point=First point
For a=1 To pn
world.point=After world
Next
Return world\x
End Function

Function GetPointY(pn)
world.point=First point
For a=1 To pn
world.point=After world
Next
Return world\x
End Function

Function SetPointX(pn,r)
world.point=First point
For a=1 To pn
world.point=After world
Next
world\x=r
End Function

Function SetPointY(pn,r)
world.point=First point
For a=1 To pn
world.point=After world
Next
world\y=r
End Function



Dan(Posted 2015) [#2]
here is a working verlet demo
maybe you can read out the needed parts.