2D water fluid
Posted: Wed Dec 03, 2025 7:36 pm
Another interesting for my code with the help of AI
The cursor is too way slow, i have put the float but i can make more fast, not precise though....
Code: Select all
EnableExplicit
#Width = 800
#Height = 400
; --- PHYSICS PARAMETERS ---
#Segments = 200 ; number of water points
#Stiffness = 0.025 ; main spring stiffness
#Spread = 0.25 ; lateral propagation
#Damping = 0.025 ; wave damping
#RestHeight = #Height / 2 ; water rest height
Dim Height.f(#Segments) ; current height
Dim Velocity.f(#Segments) ; vertical speed
Dim LeftDelta.f(#Segments)
Dim RightDelta.f(#Segments)
Define i, x, mx.f, my.f
Define dx.f, dy.f
Define event
; Function to draw the circle cursor
Procedure DrawCircleCursor()
Shared mx.f
Shared my.f
Protected r = 8 ; cursor radius
mx = MouseX()
my = MouseY()
; Draw a transparent light-blue circle
;Circle(mx, my, r, RGBA(0, 180, 255, 180))
; White border for visibility
Circle(mx, my, r, RGBA(255, 255, 255, 200))
EndProcedure
InitSprite()
InitMouse()
InitKeyboard()
If OpenWindow(0, 0, 0, #Width, #Height, "2D Water Fluid", #PB_Window_ScreenCentered)
If OpenWindowedScreen(WindowID(0), 0, 0, #Width, #Height)
; Initialization
For i = 0 To #Segments
Height(i) = #RestHeight
Next
; --- Main loop ---
Repeat
event = WindowEvent()
; --- CLICK INTERACTION ---
If ExamineMouse()
If MouseButton(#PB_MouseButton_Left)
Define idx = mx * #Segments / #Width
If idx >= 0 And idx <= #Segments
Velocity(idx) - 12 ; vertical splash impact
EndIf
EndIf
EndIf
; --- PHYSICS : MAIN SPRING ---
For i = 0 To #Segments
dy = #RestHeight - Height(i)
Velocity(i) + dy * #Stiffness
Velocity(i) * (1 - #Damping)
Height(i) + Velocity(i)
Next
; --- PHYSICS : LATERAL PROPAGATION ---
For i = 0 To #Segments - 1
LeftDelta(i) = #Spread * (Height(i) - Height(i+1))
Velocity(i+1) + LeftDelta(i)
RightDelta(i) = #Spread * (Height(i+1) - Height(i))
Velocity(i) + RightDelta(i)
Next
; --- DRAWING ---
StartDrawing(ScreenOutput())
Box(0, 0, #Width, #Height, RGB(0, 0, 50)) ; dark blue background
; Water color
Define blue = RGB(0, 140, 255)
; Convert segments → screen
For i = 0 To #Segments-2
x = i * #Width / #Segments
dx = (i+1) * #Width / #Segments
LineXY(x, Height(i), dx, Height(i+1), blue)
; Fill under the water surface
LineXY(x, Height(i), x, #Height, RGB(0, 60, 120))
LineXY(dx, Height(i+1), dx, #Height, RGB(0, 60, 120))
Next
; --- Custom circle cursor ---
DrawCircleCursor()
StopDrawing()
FlipBuffers()
ExamineKeyboard()
Until event = #PB_Event_CloseWindow Or KeyboardPushed(#PB_Key_Escape)
EndIf
EndIf