{"id":7794,"date":"2013-10-01T00:00:35","date_gmt":"2013-10-01T04:00:35","guid":{"rendered":"http:\/\/blog.xamarin.com\/?p=7794"},"modified":"2013-10-01T00:00:35","modified_gmt":"2013-10-01T04:00:35","slug":"make-games-with-xamarin-ios-and-sprite-kit","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/make-games-with-xamarin-ios-and-sprite-kit\/","title":{"rendered":"Make Games with Xamarin.iOS and Sprite Kit"},"content":{"rendered":"<p dir=\"ltr\">Sprite Kit is the first game framework directly from Apple, and is fully supported by our recent <a href=\"\/ios-7-and-xamarin-ready-when-you-are\/\" target=\"_blank\">Xamarin.iOS release for iOS 7<\/a>. Sprite Kit is a framework for creating 2D games on iOS 7 and on OS X Mavericks, and includes support for many of the things you would expect in a 2D game platform including:<\/p>\n<p><img decoding=\"async\" class=\"alignright size-full wp-image-7828\" alt=\"monkey\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/monkey.png\" width=\"97\" height=\"138\" \/><\/p>\n<ul>\n<li>\n<p dir=\"ltr\">Animations<\/p>\n<\/li>\n<li>\n<p dir=\"ltr\">Collision detection<\/p>\n<\/li>\n<li>\n<p dir=\"ltr\">Particle systems<\/p>\n<\/li>\n<li>\n<p dir=\"ltr\">Rigid-body physics<\/p>\n<\/li>\n<li>\n<p dir=\"ltr\">Audio support<\/p>\n<\/li>\n<li>\n<p dir=\"ltr\">Video support<\/p>\n<\/li>\n<\/ul>\n<p dir=\"ltr\">What&#8217;s more, Sprite Kit is is tightly integrated with iOS, easily allowing such things as blending UIKit within a Sprite Kit game, or even supporting Core Image filters.<\/p>\n<p dir=\"ltr\">With Sprite Kit, games are organized into scenes (SKScene), which represent each screen within a game. The view class to use with Sprite Kit is SKView. To display a scene you simply call the view&#8217;s PresentScene method, passing it an SKScene instance.<\/p>\n<p dir=\"ltr\">The following code shows how to use an SKView within a controller to present a scene:<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic override void LoadView ()\n{\n    base.LoadView ();\n\n    View = new SKView {\n        ShowsFPS = true,\n        ShowsNodeCount = true,\n        ShowsDrawCount = true\n    };\n}\n\npublic override void ViewWillLayoutSubviews ()\n{\n    base.ViewWillLayoutSubviews ();\n\n    var view = (SKView)View;\n\n    if (view.Scene == null) {\n        var scene = new MonkeyScene (View.Bounds.Size);\n        scene.ScaleMode = SKSceneScaleMode.AspectFill;\n        view.PresentScene (scene);\n    }\n}\n<\/pre>\n<p>As you can see, the SKView class includes several properties that can be set for diagnostics:<\/p>\n<ul>\n<li>ShowsFPS &#8211; Shows the frame rate.<\/li>\n<li>ShowsNodeCount &#8211; Shows the number of rendering passes.<\/li>\n<li>ShowsDrawCount &#8211; Shows the number of visible nodes.<\/li>\n<\/ul>\n<p>When these are set to true, the metrics are displayed in the lower right of the screen, as shown below:<\/p>\n<p><img decoding=\"async\" alt=\"\" src=\"https:\/\/lh4.googleusercontent.com\/eJ0mBgK1eAAeQx7xCsekKdaDPq6GLdqnLmGD4H7zwnsD2zBriPHGX8t-5FYh2uMdpydMXp9SupoMzFe4lvGMQa48U4R3TBF3f7HRBfmfMbkwqORh58RTc_yH\" width=\"207px;\" height=\"417px;\" \/><\/p>\n<p>Since games don&#8217;t often want the status bar displayed, it&#8217;s a good idea to hide it, which in iOS 7 you can take care of within the controller by overriding PrefersStatusBarHidden:<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic override bool PrefersStatusBarHidden ()\n{\n    return true;\n}\n<\/pre>\n<p>The MonkeyScene class inherits from SKScene:<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic class MonkeyScene : SKScene\n{\n}\n<\/pre>\n<p>The scene is where you build up a hierarchy of nodes. The base class for all the visual elements in Sprite Kit is SKNode. The SKScene is an SKNode. Additionally all the sprites you add to a game are SKNodes as well. Sprites are nodes that represent the images that appear in the game. In Sprite Kit the SKSpriteNode class represents a sprite.<\/p>\n<p>For example, the following code creates a sprite from an image called frame-1.png (the extension isn\u2019t required), positions it in the center of the scene and adds it to the scene:<\/p>\n<pre class=\"lang:csharp decode:true\">\nSKSpriteNode monkey;\npublic MonkeyScene (SizeF size) : base(size)\n{\n    monkey = SKSpriteNode.FromImageNamed (&quot;frame-1&quot;);\n    monkey.Position = new PointF (Size.Width \/ 2, Size.Height \/ 2);\n    AddChild (monkey);\n}\n<\/pre>\n<p>Running this displays the image:<\/p>\n<p><img decoding=\"async\" alt=\"\" src=\"https:\/\/lh5.googleusercontent.com\/k3LH_wzhWuwqRFRweNySn_F7YzejQLLgG66ljeFjhMEKSXAHRJbpGo1omVAyz2xhZDq0xl9-jytdznZ7S6uyp8UbnmWvrmc4xAT2H3SNytyC36y26T3QagY_\" width=\"207px;\" height=\"417px;\" \/><\/p>\n<p>Adding a sprite is the most fundamental thing you can do in Sprite Kit. But of course, to make a game, you&#8217;ll need the sprite to do more than just sit there. This is where actions can be used. Actions (SKAction) are a way to essentially script what you want to have happen in a game. There are a plethora of actions available, allowing everything from moving sprites, to rotating, scaling and animating them. There are even actions to chain other actions together in a sequence, as well as to group them.<\/p>\n<p>Let&#8217;s make our monkey move around the screen to wherever the user touches. The simplest way to do this is by overriding one of the touch handling methods in SKScene (although you could use gesture recognizers as well). To run an action on a sprite we simply call the sprite&#8217;s RunAction method, passing it the action. In this case we use the MoveTo action to move the sprite to the touch location:<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic override void TouchesBegan (NSSet touches, UIEvent evt)\n{\n    base.TouchesBegan (touches, evt);\n    var touch = (UITouch)touches.AnyObject;\n    monkey.RunAction (SKAction.MoveTo (touch.LocationInNode (this), 1));\n}\n<\/pre>\n<p>Now the monkey moves to wherever the user touches the screen. However, it doesn&#8217;t look quite right to have the monkey sliding around. Let&#8217;s add an animation to make it look like the monkey is walking as he moves.<\/p>\n<p>To accomplish, we can add a bunch of images to create a sprite based animation where each image represents an animation frame. We use another action, AnimateWithTextures, to cycle through the textures to create the animation, along with RepeatActionForever to loop the animation:<\/p>\n<pre class=\"lang:csharp decode:true\">\nSKAction animate;\npublic MonkeyScene (SizeF size) : base(size)\n{\n    ...\n    var textures = Enumerable.Range (1, 8).Select (\n        (i) =&gt; SKTexture.FromImageNamed (String.Format (&quot;frame-{0}&quot;, i))).ToArray ();\n    animate = SKAction.RepeatActionForever (SKAction.AnimateWithTextures (textures, 0.1));\n}\n<\/pre>\n<p>In the touch handling code, simply run the animation. Also remove all the actions when the movement stops so as to stop the monkey from running in place:<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic override void TouchesBegan (NSSet touches, UIEvent evt)\n{\n    base.TouchesBegan (touches, evt);\n    var touch = (UITouch)touches.AnyObject;\n    AnimateMonkey (touch.LocationInNode (this));\n}\nvoid AnimateMonkey (PointF location)\n{\n    monkey.RunAction (animate);\n    monkey.RunAction (SKAction.MoveTo (location, 1), () =&gt; {\n        monkey.RemoveAllActions ();\n    });\n}\n<\/pre>\n<p>If we run the game now, the monkey animates as he moves around, as this video of the monkey running around on an iPhone 5 shows:<\/p>\n<p>[youtube http:\/\/www.youtube.com\/watch?v=4FpkIXKJq1U]<\/p>\n<p>You can download the code from this blog post <a href=\"https:\/\/github.com\/mikebluestein\/SpriteKitDemo\" target=\"_blank\">here<\/a>.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sprite Kit is the first game framework directly from Apple, and is fully supported by our recent Xamarin.iOS release for iOS 7. Sprite Kit is a framework for creating 2D games on iOS 7 and on OS X Mavericks, and includes support for many of the things you would expect in a 2D game platform [&hellip;]<\/p>\n","protected":false},"author":1932,"featured_media":39167,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[6,4],"class_list":["post-7794","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-ios","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Sprite Kit is the first game framework directly from Apple, and is fully supported by our recent Xamarin.iOS release for iOS 7. Sprite Kit is a framework for creating 2D games on iOS 7 and on OS X Mavericks, and includes support for many of the things you would expect in a 2D game platform [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/7794","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/1932"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=7794"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/7794\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/39167"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=7794"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=7794"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=7794"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}