Vehicle Physics Code Example?

BlitzMax Forums/BlitzMax Programming/Vehicle Physics Code Example?

zoqfotpik(Posted 2012) [#1]
Didn't there used to be a code sample under /projects/samples showing different types of topdown vehicle physics? Seems like there was a car, a tank, a jet, maybe a rocket? I can't find it now-- has it been removed?


GW(Posted 2012) [#2]
Here is a bit of Monkey code for simple car physics.
Searching the forums will give you more elaborate examples.
Class TCar
	Const MAXPOWER# = 0.1
	Const MAXTURN# = 0.6
	
	field positionX# = 400
	field positionY# = 300
	
	field velocityX#
	field velocityY#
	
	field drag# = 0.97
	field angle# = 0
	
	field angularVelocity# 
	
	field angularDrag# =0.8
	
	field power# = 0'0.6
	field turnSpeed# = 0.7

	Method New()
	
	End Method
	
	Method ControlViaKeys:Void()
		If KeyDown(KEY_UP) Then 
			power += 0.001
			If power > MAXPOWER Then power = MAXPOWER
			velocityX += Sin(angle) * power;
			velocityY += Cos(angle) * power;
		Else
			power *= 0.7 
		Endif
		
		If KeyDown(KEY_DOWN) Then 
			velocityX *= 0.9		
			velocityY *= 0.9
		Endif
		
		If KeyDown(KEY_LEFT) Then 
			angularVelocity += turnSpeed 
		Endif
		
		If KeyDown(KEY_RIGHT) Then 
			angularVelocity -= turnSpeed
		EndIf

	End Method 
	
	Method UpdatePhysics:Void()
		positionX += velocityX
		positionY += velocityY
		velocityX *= drag
		velocityY *= drag
		angle += angularVelocity
		angularVelocity *= angularDrag
		
		
	'	If positionX < 0 Then positionX  = 799
	'	If positionY < 0 Then positionY  = 599
	'	If positionX > 800 Then positionX  = 0
	'	If positionY > 600 Then positionY  = 0
		
		turnSpeed =  Max(Abs(velocityX),Abs(velocityY))/2
		turnSpeed = Min(MAXTURN, turnSpeed)

	End Method
End 	



zoqfotpik(Posted 2012) [#3]
That's more than sufficient for my purposes. There is one small issue with it-- once you are no longer stepping on the gas, any rotation turns into a drift. That's probably OK though, I am not doing anything that needs to seem realistic.