VBfx / Tile tutorial / Sample

Smooth direction change

This effect is done by acceleration and braking instead of just setting the camera speed. Note that I had to extend the Type again and the angle calculation was dropped from the LookAt function.

New Type

Public Type tCamera
    'Current position
    X as Single
    Y as Single
    
    'Requested position
    DestX as Long
    DestY as Long
    
    'Next requested position
    NextX as Long
    NextY as Long
    
    'Movement
    Angle as Single
    Speed as Single
    
    'Screen size
    w as Long 'W means width
    h as Long 'H means height
    
    'Number of tiles that fit on screen
    TilesX as Long
    TilesY as Long
    
    'Front buffer
    FrontDC as Long
End Type

New LookAt

Public Sub LookAt( iX as Long, iY as Long, iSmooth as Boolean )
    With Camera
        'Set requested position
        .NextX = iX
        .NextY = iY
        
        If Not iSmooth Then
            'Set current position
            .X = iX
            .Y = iY
            
            'Check position
            Clip
        End If
    End With
End Sub

New UpdatePosition

Public Sub UpdatePosition()
    Dim Dist as Long
    Dim NewSpeed as Single
    Static NextMove as Long
    
    With Camera
        'Timing
        If NextMove > GetTickCount Then: Exit Sub
        NextMove = GetTickCount + 20 'Update at 50 FPS
        
        'Get distance
        Dist = Distance( CLng( .X ), CLng( .Y ), .DestX, .DestY )
        
        If ( .DestX = .NextX ) And ( .DestY = .NextY ) Then
            'Exit when target reached
            If Dist = 0 Then: Exit Sub
            
            'Get speed
            NewSpeed = Dist * 0.2
            If NewSpeed > 24 Then: NewSpeed = 24
            
            'Apply acceleration
            If .Speed < NewSpeed Then: .Speed = .Speed + 1
            If .Speed > NewSpeed Then: .Speed = NewSpeed
        
        Else
            'Brake
            .Speed = .Speed * 0.8
            
            'Change target when slow enough
            If .Speed < 1 Then
                .Speed = 0
                
                'Set new target
                .DestX = .NextX
                .DestY = .NextY
                
                'Continue in the next frame
                Exit Sub
            End If
        End If
        
        'Calculate angle
        .Angle = GetAngle( .X, .Y, CSng( .DestX ), CSng( .DestY ) )
        
        'Move camera
        .X = .X + Cos( .Angle ) * .Speed
        .Y = .Y + Sin( .Angle ) * .Speed
        Clip
    End With
End Sub

Sample code

And for those who didn't get it all, here's the sample download:

Navigation