Playdate Pulp - Sin/Cos functions

February 02, 2022

Update 2/8/2022

PulpScript has an update that includes sine, cosine, tangent, radians, and degrees functions, so this tutorial is no longer be necessary.


This will be helpful to some. I make helper functions to estimate sin and cos functions. I used Taylor series to estimate. Here's an example drawing a dot at the position of the crank:

Player
on crank do
    // Draw a crank dot
    a = event.aa
    a /= 180
    a *= 3.14159
    call "sin"
    call "cos"
    x = sin
    x *= 32 // Scales the radius on the X axis
    x += 32 // Moves the center point right
    x += 2

    y = cos
    y *= 32 // Scales the radius on the Y axis
    y += 32 // Moves the center point down
    y += 2
end

on draw do
    fill "white" at x,y,4,4
end

on sin do
    aNorm = a
    while aNorm>=3.141592 do
        aNorm -= 6.283184
    end

    n = 0
    modifier = 1
    sin = 0
    while n<6 do
        // modifier * aNorm^(2n+1)
        // -------------------
        // (2n+1)!
        pow = n
        pow *= 2
        pow += 1

        // numerator
        num = modifier
        p = pow
        while p>0 do
            num *= aNorm
            p--
        end

        // denominator
        f = pow
        den = 1
        while f>0 do
            den *= f
            f--
        end
        if den==0 then
            den = 1
        end

        // Add to result
        num /= den
        sin += num

        // Set up next loop
        modifier *= -1
        n += 1
    end
end

on cos do
    oldA = a
    oldSin = sin
    a += 1.57079
    call "sin"
    cos = sin
    cos *= -1 // Trig is y up, pulp is y down
    a = oldA
    sin = oldSin
end

the n < 6 is the number of iterations, and I've found 6 is good enough for three decimal places.

Here's an example of using the sin and cos functions to draw squares around a point.

This is a concept that I haven't figured out where it's going yet.