Share My Creation Rasterization Algorithms

In researching different ways to do collision detection on my game, I accidentally discovered what can be an alternative to Bresenham's algorithm.


What is Bresenham's algorithm?
Bresenham's line algorithm is an algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points.

300px-Bresenham.svg.png

https://en.wikipedia.org/wiki/Bresenham's_line_algorithm



What did I accomplish?

Despite not exactly being the collision detection solution I was looking for, the end-result ended up being pretty similar to what has been described above:

Untitled_2.png

My algorithm (B4J): getBlocks2()


The B4J Project
In the code, you'll see two different approaches: getBlocks() and getBlocks2().
The first approach is what will end-up in my collision detection routines.
The second approach is my accidentally discovered "Bresenham's algorithm".

B4X:
'Bruno's Bresenham's algorithm ;)
Sub getBlocks2(x1 As Double, y1 As Double, x2 As Double, y2 As Double, blockSize As Double) As List
    Dim blocks As List
    Dim stepX, stepY As Double 
    blocks.Initialize
 
    Dim dX = (x2 - x1) As Double
    Dim dY = (y2 - y1) As Double
    If (x1 = x2) And (y1 = y2) Then
        stepX = 0
        stepY = 0
        'Log("It's a point!")
    Else if (x1 = x2) And (y1 <> y2) Then
        stepX = 0
        stepY = blockSize
        'Log("It's a vertical line!")
    Else if (x1 <> x2) And (y1 = y2) Then
        stepX = blockSize 
        stepY = 0
        'Log("It's a horizontal line!")
    Else
        Dim absDx = Abs(dX) As Double
        Dim absDy = Abs(dY) As Double
        If absDx > absDy Then         
            stepX = blockSize
            stepY = (absDy / absDx) * blockSize         
        Else
            stepX = (absDx / absDy) * blockSize
            stepY = blockSize         
        End If     
    End If
    If dX < 0 Then stepX = -stepX
    If dY < 0 Then stepY = -stepY
 
    Dim pX = x1 As Double
    Dim pY = y1 As Double
    Dim xx = 0, yy = 0 As Int
    Do Until Abs(pX - x1) > Abs(dX) Or Abs(pY - y1) > Abs(dY)
        blocks.Add(Array As Double((Floor(pX / blockSize) + xx) * blockSize, (Floor(pY / blockSize) + yy) * blockSize))
        pX = pX + stepX / 10
        pY = pY + stepY / 10
    Loop
    blocks.Add(Array As Double((Floor(x2 / blockSize) + xx) * blockSize, (Floor(y2 / blockSize) + yy) * blockSize))
    Return blocks
End Sub


Enjoy! :)
 

Attachments

  • BresenhamAlternative.zip
    1.8 KB · Views: 293
  • test.jar
    314.4 KB · Views: 295
Last edited:
Top