VBfx / Tile tutorial / Step 1

Distance

You surely heard of Pythagoras in school. I like this guy because he invented one of the formulas you can really use sometimes in live. For game programming this is all common basics, however. I pre-made this function for you so you don't have to dig in your math books:

Public Function Distance( X1 as Long, Y1 as Long, X2 as Long, Y2 as Long ) as Long
    'Return delta (distance)
    Distance = Sqr( CDbl( X2 - X1 ) ^ 2 + CDbl( Y2 - Y1 ) ^ 2 )
End Function

I'ts nothing more than Pythagoras, really.

GetAngle

Now the second function is a little harder and longer. The function takes 2 points and returns the angle between them (in rad). You really don't have to understand this, it's a general maths function you can copy and use.

Public Function GetAngle( X1 as Single, Y1 as Single, X2 as Single, Y2 as Single ) as Single
    Dim TempX as Single
    Dim TempY as Single
    Dim Angle as Single
    
    'Get difference
    TempX = ( X2 - X1 )
    TempY = ( Y2 - Y1 )
    
    'Special case X
    If TempX = 0 Then
        If Y2 > Y1 Then
            Angle = Pi * 0.5
        ElseIf Y2 < Y1 Then
            Angle = Pi * 1.5
        End If
    
        'Return angle
        GetAngle = Angle
        Exit Function
    End If
    
    'Special case Y
    If TempY = 0 Then
        If X2 > X1 Then
            Angle = 0
        ElseIf X2 < X1 Then
            Angle = Pi
        End If
    
        'Return angle
        GetAngle = Angle
        Exit Function
    End If
    
    'Get angle
    Angle = Atn( Abs( TempY ) / Abs( TempX ) )
    
    'Calculate angle
    If TempX < 0 And TempY > 0 Then: Angle = Pi - Angle
    If TempX < 0 And TempY < 0 Then: Angle = Pi + Angle
    If TempX > 0 And TempY < 0 Then: Angle = Pi2 - Angle
    
    'Put in range
    If Angle < 0 Then: Angle = Angle + Pi2
    
    'Return angle
    GetAngle = Angle
End Function

Put both functions into a new Module named mMath. But to make it work you also need the Pi declarations in this Module:

'Consts
    Public Const Pi as Single = 3.141593
    Public Const Pi2 as Single = 6.283185

So that's it for the moment, let's start extending the camera!

Navigation