'Physics demo
'By Jim Shaw

open window 640,512

'Three controls, accelerator, brake, and steering.
'Let's assume they're binary inputs (either on or off).
'Let's also assume the ground is flat, so gravity's not a problem.
'Then we only have 3 forces to work with:
'A - car's acceleration due to accel button held down
'B - car's deceleration due to brake button held down
'F - car's deceleration due to friction

'So, the car's position is X,Y, the car's velocity is VX and VY.
'VX and VY are initially 0.

VX = 0
VY = 0
D = 0
X = 320
Y = 256
STEERING_SCALE = 0.1
ACCELERATION_SCALE = 0.007
BRAKING_SCALE = 0.001
TERMINAL_VELOCITY=0.2
F = 0.00005

repeat

setdispbuf db
db = 1-db
setdrawbuf db
clear window

'Car's new position is:
X = X + VX
Y = Y + VY

'VX changes due to acceleration, braking and friction.
'We also need to know which way the car is going, and the
'magnitude of the velocity.
VMAG = sqrt(VX^2 + VY^2)

'We also need the direction we are heading.  This is
'D = ATAN(VX/VMAG, VY/VMAG)
'which is an angle between 0 and 360.

'Watch for VX, VY, VMAG being 0!  If VX and VY are 0, there
'is a problem that we don't know which way we are facing!
'In this case we could use an old (or previous) value of D.

'Having said that, there is then no reason to use ATAN to work
'out which direction we're going in, simply use D instead.

'So we do that :-)

p = peek("port1")
LEFT = and(p,128)/128 * STEERING_SCALE
RIGHT = and(p,32)/32 * STEERING_SCALE
B = and(p,8192)/8192 * BRAKING_SCALE
A = and(p,16384)/16384 * ACCELERATION_SCALE

'We can change this D using the steering controls
D = D - LEFT + RIGHT

'To apply friction, we need to subtract from VMAG, assume
'friction is a constant deceleration
VMAG = VMAG - F

'To apply braking, we need to subtract from VMAG, assume
'braking is a constant deceleration
VMAG = VMAG - B

'To apply acceleration, we need to add to VMAG, assume
'a constant acceleration
VMAG = VMAG + A

'We need to make sure by applying F and B that we didn't change direction!
VMAG = max(VMAG, 0)

'We may need to clamp to a maximum velocity too (terminal velocity)
VMAG = min(VMAG, TERMINAL_VELOCITY)

'We now have our new velocity, we need to apply it in the
'direction the car is going.

VX = VMAG * COS(D/180*3.141)
VY = VMAG * SIN(D/180*3.141)

'print the car at the new spot, and repeat from the top.
print_car()

'clamp
X=max(10,min(X,630))
Y=max(10,min(Y,502))

until (1=0)

'print a car at X,Y heading D degrees
sub print_car()

	DX = COS(D/180*3.141)*20
	DY = SIN(D/180*3.141)*20
	line X,Y to X+DX,Y+DY
	circle X+DX,Y+DY,5
end sub
 
