Updating the Scene

Now that we have our cat displayed on screen and code written to handle button presses, we need to glue these together so that the user's actions actually do something. This is where the update function comes in. Let's start implementing the function:

void BM_Scene_CatPad_update(void* data)
{
    BM_Sprite_update(&_catSprite);   //  Move the cat by number of pixels defined by its velocity

    //  Ensure that the cat does not move outside the screen
    if (_catSprite.currentXPos < 0)
        _catSprite.currentXPos = 0;

    if ((_catSprite.currentXPos + _catSprite.width) >= BM_DISPLAY_WIDTH)
        _catSprite.currentXPos = BM_DISPLAY_WIDTH - _catSprite.width;

    if (_catSprite.currentYPos < 0)
        _catSprite.currentYPos = 0;

    if ((_catSprite.currentYPos + _catSprite.height) >= BM_DISPLAY_HEIGHT)
        _catSprite.currentYPos = BM_DISPLAY_HEIGHT - _catSprite.height;

    //  Set the cutoff frequency and Q of the filter based on the cat's horizontal and vertical position position
    const float newFc = MW_AFXUnit_Utils_mapToRange(_catSprite.currentXPos, 0, BM_DISPLAY_WIDTH, BM_SCENE_CATPAD_MIN_FC, BM_SCENE_CATPAD_MAX_FC);
    const float newQ = MW_AFXUnit_Utils_mapToRange(_catSprite.currentYPos, 0, BM_DISPLAY_HEIGHT, BM_SCENE_CATPAD_MIN_Q, BM_SCENE_CATPAD_MAX_Q);
    MW_AFXUnit_SVFilter_changeParameters(&_filter, MW_AFXUNIT_SVFILTER_LPF, FS, newFc, newQ);
}

In the BM_Scene_CatPad_handleUserIO function that we created in the previous chapter, we set the velocity of the cat according to the D-pad button pressed. In order for the cat's coordinates to change, its sprite must be updated using the BM_Sprite_update() function.

Since the cat has the potential to move off-screen, there is some bounds checking that must be done. When working with multiple sprites, wrapping the bounds checking code into its own function may be helpful.

Next, we want to re-calculate the filter's coefficients based on the cat's position on screen. To do this, we use the MW_AFXUnit_Utils_mapToRange() function to map the cat's position on the screen to a filter cutoff/Q value.

MW_AFXUnit_Utils_mapToRange() is part of the MW_AFXUnit_MiscUtils library in MW_AFXUnits

The filter parameters are changed via the MW_AFXUnit_SVFilter_changeParameters() function. Note that the update function is periodically called and if the cat has not changed its position between multiple calls to update(), re-calculating coefficients can be an inefficient use of processor cycles. Re-calculating the filter coefficients when the cat's position has changed is a more efficient approach.

Finally, we can move the cat around the screen and change filter parameters but the filter will not be applied to the input audio! To apply the filter, we need to write the processAudio function.