platform example?

BlitzMax Forums/BlitzMax Beginners Area/platform example?

The Forum Archive is locked. These are the original blitzbasic.com forums, kept so their posts can still be read and searched. No new topics, replies or edits can be made here. To join the conversation, head over to the Blitz3D+ forums.

Here is a quick "no frills" example for you. I haven't made a platformer in years so the collision response might need some tweaking:

Strict

Const Gravity:Float = 1.0
Global PlatformList:TList = CreateList()


Graphics 640,480,0
SetClsColor 100,150,255

Local p1:Player = Player.Create(320,240)

Platform.Create(320,300)
Platform.Create(320,100)
Platform.Create(250,200)

Platform.Create(320,400,700,80)
While Not KeyHit(KEY_ESCAPE)
	Cls
	
	For Local p:Platform = EachIn PlatformList
		p.Render()
	Next
	p1.Update()
	p1.Render()
	
	Flip
	FlushMem
Wend


Type Platform
	Field X:Float
	Field Y:Float
	Field Width:Int
	Field Height:Int
	
	Function Create:Platform (_X:Float, _Y:Float, _Width:Int = 64, _Height:Int = 16)
		Local p:Platform = New Platform
		p.X = _X
		p.Y = _Y
		p.Width = _Width
		p.Height = _Height
		PlatformList.AddLast(p)
		Return p
	End Function
	
	Method Render()
		SetColor 0,128,0
		DrawRect X-(Width/2),Y,Width,Height
	End Method
	
End Type

Type Player
	Field X:Float
	Field Y:Float
	Field VX:Float
	Field VY:Float
	Field Width:Int
	Field Height:Int
	Field Controls:Int [4]
	
	Function Create:Player (_X:Float, _Y:Float, _Width:Int = 32, _Height:Int = 64)
		Local p:Player = New Player
		p.X = _X
		p.Y = _Y
		p.Width = _Width
		p.Height = _Height
		p.Controls = [KEY_UP,KEY_LEFT,KEY_RIGHT]
		Return p
	End Function
	
	Method Render()
		SetColor 255,128,0
		DrawRect X-(Width/2),Y-Height,Width,Height
	End Method
	
	Method Update()
		If KeyDown(Controls[1]) Then VX :+ -1 'LEFT
		If KeyDown(Controls[2]) Then VX :+ 1 'RIGHT

		'I'm most likely not using the best method
		'for jumping or collision response here
		If KeyHit(Controls[0]) And VY >= 0
			VY = -15
		End If

		Y :+ VY
		X :+ VX
		VY :+ Gravity
		VX :+ (0 - VX) * .05
		Local P:Platform = CollidedWithPlatform()
		If P
			If Y < P.Y + P.Height And Y > P.Y And VY > 0 Then
				Y = P.Y
				VY = 0
			End If
		End If
		
	End Method
	
	Method CollidedWithPlatform:Platform()
		For Local p:Platform = EachIn PlatformList
			If (p.X + p.Width/2 < X - Width/2)	Continue
			If (p.X - p.Width/2 > X + Width/2) Continue 
			If (p.Y + p.Height < Y - Height) Continue
			If (p.Y > Y) Continue 
			Return p
		Next
	End Method
End Type