PLAYBASIC SOURCE CODES


Jelly Sinus Terrain How It Works

🧪 Jelly Sinus Terrain - How It Works (Step-by-Step Guide)

By PlayBASIC Tutor
Created: May 2025

This demo renders a jelly-like, animated sinusoidal terrain using a grid of rotating, Gouraud-shaded polygons. The "wobble" is based on each vertex's distance from the center of the grid and animated in real time.










🔧 1. Setup Constants and Data Types

* `WorldSIZE#` defines how wide the virtual world is.
* `Size` controls the grid resolution.
* A typed array `Terrain()` stores the 3D coordinates and color for each vertex.

PlayBASIC Code:
Type tVertex
    x#, y#, z#      ; Original 3D position
    rx#, ry#, rz#    ; Rotated/projected 3D position
    Colour          ; Vertex color
EndType
COMMANDS USED:




🌈 2. Create a Grayscale Palette

We generate a grayscale palette based on depth. This will be used later to shade the polygons based on how far away they are.

PlayBASIC Code:
for lp = 0 to depth
    Scaler# = (depth - lp) / float(depth)
    ThisRGB = cliprange(Scaler# * 255, 0, 255)
    palette(lp) = rgb(ThisRGB, ThisRGB, ThisRGB)
next
COMMANDS USED: FLOAT | CLIPRANGE | RGB |




🎨 3. Draw the Backdrop

We create a shaded backdrop image using `shadebox`. This gives a nicer visual background behind the terrain.

PlayBASIC Code:
BackDrop = NewImage(...)
rendertoimage BackDrop
shadebox ...
rendertoscreen




🔁 4. Main Loop

Each frame, we:

* Draw the backdrop
* Capture 3D scene to render
* Update tilt and turn angles for camera rotation
* Recalculate the terrain heights
* Rotate and project the terrain
* Render the terrain polygons

PlayBASIC Code:
tilt# += 0.01
turn# += 2.3
RenderGround(Terrain(), WORLDSIZE#)
RotateVerts(Terrain(), Tilt#, Turn#, Roll#)
Render(Terrain())
COMMANDS USED:




### 🏔� 5. **RenderGround() – Build the Heightmap**

This function fills the `Terrain()` array with X/Z positions in a grid, and the Y (height) is calculated using a sinus function based on distance from the center. The result is a radial wave (like ripples in water).

PlayBASIC Code:
Map(xlp,zlp).y# = 1000 - (sin(baseangle# + angle#) * (1000 * (1 - Distance#)))
COMMANDS USED: SIN |


* `baseangle#` is animated each frame to make the wave move.
* `scaler#` affects wave frequency.



🌀 6. RotateVerts() – Rotate and Project Vertices

Each 3D point is rotated using a 3x3 rotation matrix for tilt, turn, and roll. After rotation, it’s projected to 2D screen space using perspective projection.

PlayBASIC Code:
rx# = screenX
ry# = screenY
rz# = depthZ
COMMANDS USED:


This is where the terrain "wobbles" and appears 3D.



🔺 7. **Render() – Draw the Polygons

We loop over the grid of vertices and draw **two triangles** for each quad (square) using `gouraudtri`.

Each vertex's color is affected by depth (z) using the earlier-created palette, giving us a 3D shaded look.

PlayBASIC Code:
Rgb1 = RgbAlphaMult(Rgb1, ShadeRGB)
gouraudtri ...
COMMANDS USED: RGBALPHAMULT | GOURAUDTRI |


There’s also a bonus "depth ray" line drawn for fun.



📌 Notes and Tips

* The terrain “jelly” effect is created using a sinusoidal function that changes each frame, causing the wave to pulse out from the center.
* The terrain rotates and zooms in/out smoothly with perspective.
* This demo uses a single layer of polygons. It's fast because it avoids overdraw and depth-sorting issues.
* Don’t store original and rotated values in the same array in real projects. This is just for demo simplicity.



🧠 What New Programmers Can Learn

* How to use typed arrays for storing 3D vertex data
* How to build and animate a height map
* How to rotate and project 3D points to 2D
* How to shade polygons based on depth
* How sinus functions can be used for cool animation effects




PlayBASIC Code:
; PROJECT : Lerp Ground
; AUTHOR  : PlayBASIC Tutor - https://PlayBASIC.com
; CREATED : 2/05/2025
; EDITED  : 3/05/2025
; ---------------------------------------------------------------------


    WorldSIZE#    = 7500
    Size            = 64

    Type tVertex
            x#,y#,z#
            rx#,ry#,rz#
            Colour 
    EndTYPE

    Dim Terrain(Size,Size) as tVertex

    depth    =15000    

    Camera = newcamera()
    cameracls camera,off
    Scenecachesize 1000*1000 *8
    scenemaxzdepth depth

    dim palette(depth)
    for lp =0 to depth
            Scaler#        = (depth-lp)/float(depth)
            ThisRGB        = cliprange(Scaler#*255,0,255)
            palette(lp) = rgb(ThisRGB,ThisRGB,ThisRGB)
    next
    
    
    BackDrop=NewImage(GetScreenWidth(),GetSCreenHeight())
    rendertoimage BackDrop
        // Draw the shaded backdrop        
        c1=$223344
        c2=c1*2
        shadebox 0,0,getscreenwidth(),getscreenheight(),c1,c1,c2,c2        

        rendertoscreen
    
        
    ;setfps 30
        
    // ------------------------------------------------
    do
    // ------------------------------------------------
    
        drawimage backdrop,0,0,false
        setcursor 0,0
        
        // set PlayBASIC to capture mode for 
        capturetoscene
        clsscene

            tilt#+=0.01
            turn#+=2.3

            RenderGround(Terrain(), WORLDSIZE# )
            RotateVerts(Terrain(),Tilt#,Turn#,Roll#)
            Render(Terrain())
inkmode 1
        drawcamera camera
        
        thisrgb=point(0,0)
        
        Sync
        
    // ------------------------------------------------
    loop spacekey()
    // ------------------------------------------------


    
        explicit true


Function Render(Map().tVertex )

        local Size        =getArrayelements(Map().tVertex,1)    
        local ThisRGB    =point(0,0)

        local sw=getscreenwidth()/2
        local sh=getscreenheight()*0.1
        
        local CLipZ1# = 10
        local xlp,zlp,polygons
        
        local ThisRGB    =$ffffff
        local DepthColour = $223344
        
        local rgb1,rgb2,rgb3,rgb4
        
        for zlp=0 to size-1
            local zlp2=zlp+1

            local x2#    =Map(1,zlp).rx#    
            local y2#    =Map(1,zlp).ry#    
            local z2#    =Map(1,zlp).rz#


            local    x3#    =Map(1,zlp2).rx#    
            local    y3#    =Map(1,zlp2).ry#    
            local    z3#    =Map(1,zlp2).rz#


            local Col1    =map(0,zlp).Colour
            local Col2    =map(1,zlp).Colour
            local Col3    =map(1,zlp2).Colour
            local Col4    =map(0,zlp2).Colour


            for xlp=0 to size-1

                local x1#    =x2#
                local y1#    =y2#
                local z1#    =z2#
                
                local x4#    =x3#
                local y4#    =y3#
                local z4#    =z3#

                local xlp2=xlp+1
                x2#    =Map(xlp2,zlp).rx#    
                y2#    =Map(xlp2,zlp).ry#    
                z2#    =Map(xlp2,zlp).rz#

                x3#    =Map(xlp2,zlp2).rx#    
                y3#    =Map(xlp2,zlp2).ry#    
                z3#    =Map(xlp2,zlp2).rz#

                if (z1#< CLipZ1#) or (z2#< CLipZ1#) then continue
                if (z3#< CLipZ1#) or (z4#< CLipZ1#)  then continue

                local rgb1    =Col2
                local rgb4    =Col3
                
                col2    =map(xlp2,zlp).Colour
                col3    =map(xlp2,zlp2).Colour
            
                local z#=(z1#+z2#+z3#)
                local ShadeRGB = palette((z#+z4#)/4)
                Rgb1=RgbAlphaMult(Rgb1,ShadeRGB)
                Rgb2=RgbAlphaMult(Col2,ShadeRGB)
                Rgb3=RgbAlphaMult(Col3,ShadeRGB)
                Rgb4=RgbAlphaMult(Rgb4,ShadeRGB)
                
                z#=z#/3
                if z#>10
                    capturedepth z#
                    inkmode 1+64
                    linec x1#,y1#,sw,sh,rgb1 and $010203
                    inkmode 1
                    gouraudtri x1#,y1#,rgb1,x2#,y2#,rgb2,x3#,y3#,rgb3
                endif

                z#=(z1#+z3#+z4#)/3
                if z#>10
                    capturedepth z#
                    gouraudtri x1#,y1#,rgb1,x3#,y3#,rgb3,x4#,y4#,rgb4
                endif                

            next xlp

            polygons+=xlp

    next zlp


EndFunction



Function RenderGround(Map().tVertex, WORLDSIZE# )
    
        local Size            =getArrayelements(map())    
        local VertexStep#    =WorldSIZE#/Size
        local CENTER#        =WORLDSIZE#/2
        local xlp,zlp
        local x#,z#
        static baseangle#,scaler#
    

        for zlp=0 to size
            z#=(zlp*VertexStep#)-CENTER#
            for xlp=0 to size
                    x#=(xlp*VertexStep#)-CENTER#

                    local distance#=getdistance2d(0,0,x#,z#)
                    distance#        =distance#/(WorldSIZE#)
                    local Angle#    =(360*Scaler#)*distance#

                    Map(xlp,zlp).x#=x#        
                    Map(xlp,zlp).y#=1000-(sin(baseangle#+angle#)*(1000*(1-Distance#)))
                    Map(xlp,zlp).z#=z#    
                    Map(xlp,zlp).Colour = ((xlp * $321) and $0fff) + ((zlp * $123000))
            next
        next

        Scaler#        =wrapvalue(Scaler#+0.01        ,0,10)
        baseangle#    =wrapvalue(baseangle#+1        ,0,360*10) 

EndFunction

        explicit false



      //  NOTE:  This demo stores the original and rotated
      //        vertex data in a typed array..
      //              See-> Not a good idea     

Function RotateVerts(Map().tVertex,Tilt#,turn#,roll#)

        ProjectionX#=400
        ProjectionY#=400

        cx=GetScreenWidth()/2
        cy=GetScreenHeight()/2
    
    Rem prepare the rotation matrix
        A#=Cos(tilt#):B#=Sin(tilt#)
        C#=Cos(turn#):D#=Sin(turn#)
        E#=Cos(roll#):F#=Sin(roll#)
        AD#=A#*D#
        BD#=B#*D#

    ; Calc Rotation Matrix  
          m11#=C#*E#
        m21#=-1*C#*F#
        m31#=D#
        m12#=BD#*E#+A#*F#
        m22#=-1*BD#*F#+A#*E# 
        m32#=-1*B#*C# 
        m13#=-1*AD#*E#+B#*F# 
        m23#=AD#*F#+B#*E#
        m33#=A#*C# 

        Size=GetArrayElements(Map())

        Static ZoomAngle#
        ZoomAngle#=wrapangle(ZoomAngle#+1)


    Rem rotate all the points using the matrix
    For zlp=0 To Size
        For xlp=0 To Size
            
              pointx#=Map(xlp,zlp).x
              pointy#=Map(xlp,zlp).y
              pointz#=Map(xlp,zlp).z

            rX# = (m11# * pointx#) + (m12# * pointy#) + (m13# * pointz#) 
            rY# = (m21# * pointx#) + (m22# * pointy#) + (m23# * pointz#)
            rZ# = (m31# * pointx#) + (m32# * pointy#) + (m33# * pointz#)
            
            rZ# =rZ#+ 4000 + cos(ZoomAngle#) * 2000
            
            Map(xlp,zlp).rz=rz#
            if (rz#=>10)
                    // Project point
                  Map(xlp,zlp).rx    = cx+ ((rX#*ProjectionX# ) / rz#)
                    Map(xlp,zlp).ry    = cy+ ((rY#*ProjectionY# ) / rz#)
            endif    
        Next 
  Next 
EndFunction
    
    

Storing Objects In Linked List Moving Objects Example

This PlayBASIC code demonstrates the use of **LinkedList** features for managing dynamic objects in a simple animation. Here's what the code does step-by-step:

1. Setup and Initialization:
  - The program sets the frame rate to 60 frames per second (`setfps 60`).
  - A type, `tAnimatedObject`, is defined to represent individual animated objects with attributes for position (`X#, Y#`), angle (`Angle#`), speed (`Speed#`), and color (`Colour`).

2. Dynamic Object Creation:
  - When the left mouse button is pressed (`if mb=1`), a new `tAnimatedObject` is created and added to the `LinkedList`:
    - The angle starts at `0`, representing the initial position.
    - The speed of movement is set to `4.45`.
    - A random color is assigned to the object (`rndrgb()`).

3. Object Animation:
  - The objects are animated in a circular motion around the mouse pointer:
    - The position of each object (`X#, Y#`) is calculated using trigonometric functions (`cos` and `sin`) based on its angle, spanning a radius of 100 pixels around the mouse.
    - Each object's angle is incremented by its speed, causing it to move along the circular path.

4. Object Removal:
  - If an object's angle exceeds 180 degrees, it is removed from the `LinkedList` (`if (angle# > 180) then Object = null`), simulating objects "disappearing" after completing their path on the left-hand side of the mouse pointer.

5. Visual Feedback:
  - A circle is drawn around the mouse pointer to indicate the reference position.
  - Each animated object is rendered as a circle with its assigned color at its calculated position (`circlec`).
  - The angle of each object is displayed for debugging purposes.

6. Loop:
  - The program continuously runs this logic in a loop, redrawing the screen (`cls` and `sync`) and updating all active objects.


Summary:

This demo creates and animates objects dynamically using PlayBASIC's **LinkedList** features. Objects are created when the mouse is clicked and move in a 180-degree arc around the mouse pointer, from the right-hand side to the left. They are removed from the list once they complete their arc. The code demonstrates dynamic object creation, animation, and memory management using `LinkedList` operations.


PlayBASIC Code:
    setfps 60


    type tAnimatedObject
            X#,Y#
            Angle#
            Speed#
            Colour
    endtype

    Dim object as tAnimatedobject list

    do
        cls 
        
        mx=mousex()
        my=mousey()
        mb=mousebutton()

        if mb=1
            Object = new tAnimatedobject

            Object.Angle    =  0
            Object.Speed    =  4.45
            Object.Colour    = rndrgb()
            flushmouse
        endif


        print "press mouse to create dynamic object"

        // draw a circle at mouse position        
        circle mx,my,50,true


        for each object()
            
            angle#=Object.Angle
            // Animate object
            object.X#=mx+cos(angle#)*100
            object.Y#=my+sin(angle#)*100
            circlec object.x#,object.y#,50,true,object.colour
            angle#+=object.speed#
            Object.Angle=angle#
            print angle#
            if (angle#>180) then Object = null
        next    
        Sync
    loop
COMMANDS USED: SETFPS | DIM | LIST | CLS | MOUSEX | MOUSEY | MOUSEBUTTON | NEW | RNDRGB | FLUSHMOUSE | PRINT | CIRCLE | COS | SIN | CIRCLEC | SYNC |






How the Lerp Vertex Example Works

How the Lerp Vertex Example Works (Explained for New Programmers)

This PlayBASIC program demonstrates how to create a smooth animation by **interpolating** between two shapes using a function called **LERP**, which stands for *Linear Interpolation*.

🧱 The Basic Idea

The program shows a square (made of four lines) that slowly morphs into a jumble of random lines, and then back again—over and over. This transformation is done **smoothly**, thanks to LERP, which blends between two values step by step.






🛠 Key Concepts and How It Works

  1. **Two Shapes to Interpolate Between**

    The program defines two shapes:

      `Shape1()` – a simple square made of 4 connected lines.
      `Shape2()` – a version of the square where all the points are randomized.

    Each shape is stored as an array of `tLine`, which is a custom type made of two points (`p1` and `p2`). Each point has an `x` and `y` position on the screen.


  2. The LERP Function

    The LERP function takes three values:

PlayBASIC Code:
    Lerp(V1#, V2#, Scale#)
COMMANDS USED:



It blends from `V1#` to `V2#`, depending on the `Scale#`.

* When `Scale# = 0`, the result is `V1#` (the starting point).
* When `Scale# = 1`, the result is `V2#` (the ending point).
* Values in between give you a smooth blend between the two.

3. Animation Using Cosine

  In the main loop, the variable `Scale#` is calculated like this:

PlayBASIC Code:
Scale# = (50 + Cos(Angle#) * 50) / 100
COMMANDS USED: COS |



This creates a smooth back-and-forth motion (from 0 to 1 to 0), making the square morph into the random shape and then return again.

4. **Drawing the Shapes**

Three versions of the shapes are drawn on screen:

  * The **original shape** in one color.
  * The **random shape** in a second color.
  * The **animated (interpolated) shape** in white, which moves between the two using LERP.

  This is done in the `DrawLerpedBox()` function, which blends each corner of the lines from Shape1 to Shape2.



🖱 Interactive Controls

The program reacts to your mouse:

* Left-click anywhere to create a new square at that position.
* Right-click to generate a new set of random lines for the second shape.


💡 Why This Is Useful

This type of smooth transformation is great for creating animations, UI transitions, or morphing effects in games. Learning how to use LERP gives you the power to blend anything—positions, colors, sizes, and more!



PlayBASIC Code:
; PROJECT : Lerp Vertex Example
; AUTHOR  : PlayBASIC Tutor - https://PlayBASIC.com
; CREATED : 3/05/2025
; EDITED  : 4/05/2025
; ---------------------------------------------------------------------


    openscreen 1280,720,32,true

    Type tVertex2D
            x#,y#
    EndType

    Type tLine
                p1 as tVertex2D        
                p2 as tVertex2D        
    Endtype

    Edges = 4
    Dim Shape1(Edges) as tLine
    Dim Shape2(Edges) as tLine

    InitBox(Shape1(),300,300,400,400)            
    InitRandomBox(Shape2())
    
    setfps 60

    do
        cls $334455
        
        // Draw Starting Shape
        ink $00ff
        DrawLerpedBox(Shape1(),Shape2(), 0)
        
        // Draw End Shape
        ink $ff00FF
        DrawLerpedBox(Shape1(),Shape2(), 1)
                
        Scale#=(50+cos(Angle#)*50)/100
        ink $ffffff
        DrawLerpedBox(Shape1(),Shape2(),Scale# )

        Angle#=wrapangle(angle#,1)
            
        if mousebutton()=1
                x=mousex()
                y=mousey()
                angle#=180
                Size=RndRange(100,200)
                InitBox(Shape1(),x,y,x+Size,y+Size)            
        endif            

        if mousebutton()=2
            InitRandomBox(Shape2())
            angle#=0
        endif            

        
        sync
    loop spacekey()




Function DrawLerpedBox(ThisShape1().tLine,ThisShape2().tLine, Scale#)

    Scale# = cliprange#(Scale#,0,1)    
    for lp =0 to 3

            x1#= lerp(ThisShape1(lp).p1.x,ThisShape2(lp).p1.x,Scale#)
            y1#= lerp(ThisShape1(lp).p1.y,ThisShape2(lp).p1.y,Scale#)

            x2#= lerp(ThisShape1(lp).p2.x,ThisShape2(lp).p2.x,Scale#)
            y2#= lerp(ThisShape1(lp).p2.y,ThisShape2(lp).p2.y,Scale#)
            line x1#,y1#,x2#,y2#
    next


EndFunction    







    //  Make a box shape 

Function InitBox(ThisShape().tLine,X1,Y1,X2,Y2)        


    i=0
    ThisShape(i).p1.x = x1
    ThisShape(i).p1.y = y1
    ThisShape(i).p2.x = x2
    ThisShape(i).p2.y = y1

    i++
    ThisShape(i).p1.x = x2
    ThisShape(i).p1.y = y1
    ThisShape(i).p2.x = x2
    ThisShape(i).p2.y = y2

    i++
    ThisShape(i).p1.x = x2
    ThisShape(i).p1.y = y2
    ThisShape(i).p2.x = x1
    ThisShape(i).p2.y = y2


    i++
    ThisShape(i).p1.x = x1
    ThisShape(i).p1.y = y2
    ThisShape(i).p2.x = x1
    ThisShape(i).p2.y = y1

EndFunction    



Function InitRandomBox(ThisShape().tLine)        

    sw=getscreenwidth()
    sh=getscreenheight()
    
    for lp =0 to 3
        ThisShape(lp).p1.x = rnd(sw)
        ThisShape(lp).p1.y = rnd(sh)
        ThisShape(lp).p2.x = rnd(sw)
        ThisShape(lp).p2.y = rnd(sh)
    next

EndFunction    



    







Function  Lerp(V1#,V2#,Scale#)
        Result#= V1#+((V2#-V1#)*Scale#    )
EndFunction Result#



  Related Source Code Examples

    --  Lerp Vertex  (Morphing Cube to Sphere)

Z Sorting in Software Without Traditional Sorting

In this example, we explore an efficient and surprisingly powerful method for Z-sorting objects in software—without relying on traditional sorting algorithms like quicksort or merge sort.

Instead of comparing and rearranging objects, we use a Z-depth indexed array to organize our scene. Each unique Z-depth becomes a key that points to the first object at that depth, with each object linking to the next—effectively creating linked lists per depth level. At render time, we walk this structure from the farthest (highest Z) to the closest (lowest Z), drawing each object in order.




Key Highlights:

-- Demonstrates a scene with up to 1,000,000 objects rendered in software.
-- Implements a Z-buffer using a heap + depth map array.
-- Shows the benefits of a non-comparative sorting approach (similar in spirit to radix sort).
-- Discusses practical object culling, memory usage, and overdraw.
-- Demonstrates real-time rendering performance scaling with 10K, 25K, 100K, and even 1M objects.

This method is ideal for software renderers and game devs who want fast Z-sorting without complex algorithms. Whether you're coding games in PlayBASIC or just interested in alternative sorting strategies, this video offers a great breakdown of a simple but effective approach.
#1
2025-07-02 - Fast Z Sorting Objects.zip (5.52 KB)

Manually Doing Pixel Perfect Sprite Collisions (Examples & Video)

Manually Doing Pixel Perfect Sprite Collisions (Examples & Video)

In this example we look over three methods for doing Pixel Perfect sprite collisions manually in program code, rather than using the built in sprite collision method (see SpriteCollisionMode) .

Sprite Collision Method 1: Raw Image (point by point) - The first example computes the common area the two sprites share and then reads the source pixels from the source sprite, checks for a mask colour then does the same for the Destination sprite. If the two pixels are Not mask colour, then we have a collision. This method works but there's a lot of surface overhead constantly pulling individual pixels from the surfaces via Point()


Sprite Collision Method 2: Byte Mask (Preprocess images into a 8bit Collision Mask) - The second method actually works almost the same as the first, except this time we create a collision mask of each image. The mask is an 8 bit version of the image, where each byte in the mask is either 0 for transparent or 1 for solid. The sprite collision routine then uses the same logic as method #1 but directly reads the mask bytes rather than reading pixels. This means it doesn't matter what type of image format (video/ FX/ AFX) the cost of reading the mask is the same regardless.


Sprite Collision Method #3: Span Buffer (Preprocess the images into a span list of hard pixels only) - The last method we look at is an extension to the mask concept, expect rather than store pixel data, we scan the image and make list of hard spans (none transparent pixels) for each row. Each span is just two values, the starting coordinate and length of the span. The data structure contains a table at the top of offsets into the span list, so we can look up each row as need be. Rows with no solid pixels, don't create any data, so we're only every comparing solid pixels to solid pixels. The regions might not overlap, but for most sprites it all boils down to only a couple of compares per row..


PlayBASIC has a number of sprite collision methods built in, ranging from simple bounding box intersections, rotated bounding box, Vector Shape ( Polygon Collision supporting Convex / Concave & complex polygons), Various sliding methods through to Pixel Perfect collision mode.



Video





Sample Code

This is the pixel perfect sprite collision function from the first demo, it basically just computes if the two sprites share a common area and then runs through the pixel data point() by point() exiting when it finds two pixels that aren't mask colour



PlayBASIC Code:
; *=---------------------------------------------------------------------=*
; *=---------------------------------------------------------------------=*
; *=---------------------------------------------------------------------=*
;>> Sprite Hit Pixels <<
; *=---------------------------------------------------------------------=*
; *=---------------------------------------------------------------------=*
; *=---------------------------------------------------------------------=*
;   This function check if two spites overlap at pixel level. 
;
;
; *=---------------------------------------------------------------------=*

constant SpriteHitPixels_DEBUG = false


function SpriteHitPixels(SrcSprite,DestSprite)

SrcX1=GetSpriteX(SrcSprite)+GetSpriteHandleX(SrcSprite)
SrcY1=GetSpriteY(SrcSprite)+GetSpriteHandleY(SrcSprite)
SrcWidth=GetSpriteWidth(SrcSprite)
SrcHeight=GetSpriteHeight(SrcSprite)


DestX1=GetSpriteX(DestSprite)+GetSpriteHandleX(DestSprite)
DestY1=GetSpriteY(DestSprite)+GetSpriteHandleY(DestSprite)
DestWidth=GetSpriteWidth(DestSprite)
DestHeight=GetSpriteHeight(DestSprite)

// Manually check if the two sprites at least share the same area

; 
if (SrcX1+SrcWidth) > DestX1
if SrcX1<(DestX1+DestWidth)

if (SrcY1+SrcHeight) > DestY1
if SrcY1<(DestY1+DestHeight)

//Status=true

// Scan through smallest region of the two
OldSurface=GetSurface()

SrcImage=GetSpriteImage(SrcSprite)
SrcImageMaskColour =GetImageMaskColour(SrcImage)

DestImage=GetSpriteImage(DestSprite)
DestImageMaskColour =GetImageMaskColour(DestImage)


// Compute the rect the two images share
ClipX1=MaxVal(SrcX1,DestX1)
ClipX2=MinVal(SrcX1+SrcWidth,DestX1+DestWidth)

ClipY1=MaxVal(SrcY1,DestY1)
ClipY2=MinVal(SrcY1+SrcHeight,DestY1+DestHeight)


#IF SpriteHitPixels_DEBUG=true
Boxc DestX1,DestY1,DestX1+DestWidth,DestY1+DestHeight,False, Rgb(255,0,0)
Box ClipX1,ClipY1,ClipX2,ClipY2,false
#ENDIF


// Translate the world space cords to local 
// image space cordinates

OffsetX =SrcX1 -DestX1
OffsetY =SrcY1 -DestY1


ClipX1 -=SrcX1
ClipX2 -=SrcX1
ClipY1 -=SrcY1
ClipY2 -=SrcY1

OldSurface=GetSurface()


// Brute force scan through images
for ScanLPY = ClipY1 to ClipY2

  // Check if this row overlap
rendertoimage SrcImage
for ScanLPX = ClipX1 to ClipX2

ThisPixel1=Point(ScanLPX,ScanLPY)
if ThisPixel1!=SrcImageMaskColour

rendertoimage DestImage

  ThisPixel2=Point(OffsetX+ScanLPX,OffsetY+ScanLPY)
if ThisPixel2!=DestImageMaskColour
STATUS=TRUE

#IF SpriteHitPixels_DEBUG=false
 eXITfor ScanLpY
#endif

#IF SpriteHitPixels_DEBUG=true
rendertoimage 0
dotc OffsetX+ScanLPX,OffsetY+ScanLPY,$00ff00;ThisPixel2
#endif
endif
rendertoimage SrcImage
endif
next
next

rendertoimage OldSurface

endif
endif

endif
endif

EndFunction Status


#1
2018-04-21 - Pixel Perfect Collision.zip (28.09 KB)