CocosSharp helper methods for the "Give us the Gist of it!" contest

Xamarin recently ran a "Give us the Gist of it!" contest, encouraging developers to share snippets of code they found useful in day to day Xamarin work. From the valid entries, five were randomly chosen as winners, and yours truly happened to be one of them. I will soon be adding a "limited edition long-sleeve Xamarin T-Shirt" to my growing mountain of Xamarin swag.

I submitted two gists, the first was InlineTableViewSource - a subclass of UITableViewSource that lets you define the delegate/datasource methods inline using object initialiser syntax. The second was the set of CocosSharp helpers I used in the meetup-pop sample I posted about earlier. I promised in those posts that I would cover the extension methods I used, so this is the perfect segue.

CocosSharp Extension Methods

The full set of helpers is available as a gist that can be pasted straight into a LINQPad query with the CocosSharp package, then executed to show a basic sample.

Highlights from the class include:

  • Awaitable CCNode.RunActionsWithTask - allows you to await the running of a set of actions (for example, in order to not proceed with subsequent code till an animation completes), without having to explicitly calculate the duration of the actions or use a callback.
  • Easy relative positioning with CCNode.PlaceAt - allows you to position a CCNode relative to the boundaries of a parent CCNode. Fluent style, so can be used at initialisation time.
  • Easy filled colours with CCDrawNode.FillWith and quick sprite initialisation with CCNode.WithSprite, also fluent.
  • Quick insetting or outsetting with CCSize.MultiplyBy.

A sample that demonstrates a majority of the items fairly concisely:

public static async void DoExample(this CCLayer @this)  
    // create a container for the banner and label, rotated slightly and zoomed heavily
    var container = new CCNode()
        ContentSize = new CCSize(@this.VisibleBoundsWorldspace.MaxX*.75f, @this.VisibleBoundsWorldspace.MaxY*.1f),
        Scale = 5f,
        Rotation = -22.5f,
    }.PlaceAt(.5f, .35f, @this);

    // fill the container with a red coloured banner
    var filledBanner = new CCDrawNode() {ContentSize = container.ContentSize}
        .PlaceAt(.5f, .5f, container);

    // place a label in the center of the banner with centered text
    var newLabel = new CCLabel("LABEL!", "consolas", 48f)
        .PlaceAt(.5f, .5f, container);

    // animate the container to size with a bounce effect, simulating a "stamp" effect from behind the screen
    // do not proceed till the animation completes
    await container.RunActionsWithTask(new CCEaseBounceOut(new CCScaleTo(1f, 1f)));

    // once the animation has completed, changed the colour and label text
    newLabel.Text = "The animation is done!!";