Friday, July 13, 2012

Interlude 8 - A Simpler Starfield (Updated 23/01/16)

Webcomic Courtesy of Ethanol & Entropy

We have been using the Twinkle class written by Ipad41001 to produce our star-field effect in MineSweeper, and a very fine class it is. However it is a touch computationally expensive if there is a bit else going on at the same time.

On the "hard" difficulty using our first generation iPad, the frame rate per second is around 14-15 using the Twinkle class. This doesn't effect gameplay but the twinkles are a bit slow.

If your game is more frame rate critical or you just want a different look then you could use the following function instead of this class. Using this star field effect gives us an extra 4-5 frames per second.

In your Main class, you will need:

-- Main

-- A variable to hold the number of stars to display on the screen,
-- the smaller the number of stars the quicker this function will run.
-- Note that this is a local variable and only available in the Main Class

local NUMSTARS = 50

-- In the setup function you need to initialise the table 
-- which will hold your stars

function setup()
    
    -- define black colour to make our code more readable

    blackColour = color(0, 0, 0)

    -- Initialise the stars table which contains the x and y screen co-ordinates
    -- for each star. These are set to a random position between 1 and the screen
    -- height and width.

    stars = {}
    for i = 1, NUMSTARS do
        stars[i] = {x = math.random(WIDTH), y = math.random(HEIGHT)}
    end

end

Add the following function to draw the star field.

function drawStarField()

    -- Star Field function courtesy of Javier Moral
    -- from his Fireworks example

    for i = 1, NUMSTARS do

        -- Set the fill colour to white and a random transparency, 
        -- this is half of the twinkle effect.

        fill(255, 255, 255, math.random(255))

        -- Each star is represented by a small rectangle. 
        -- The random x and y co-ordinate of
        -- the star was initialised in the setup() function, 
        -- so the stars don't move. The width 
        -- and height of each rectangle is set to a random integer 
        -- between 1 and 3 each frame.
        -- Codea will try and call draw() 60 times per second.

        rect(stars[i].x, stars[i].y, math.random(3), math.random(3))

    end

end

and then call it in the draw() function:

function draw()

    -- Set the background colour to black

    background(blackColour)

    -- Call the star field function

    drawStarField()

end

No comments:

Post a Comment