Tag Archives: Cocos2d-XNA

Cocos2D-XNA Tutorial 2: Basic Actions

In my last post (Cocos2D-XNA Tutorial 1: Basic Sprites), I explored some of the basic ways that sprites in Cocos2D-XNA (C2D from here on) could be used in a game.  In that project, I changed properties on the sprite object directly to perform different actions, such as movement, scaling, rotation, etc.  In some cases, this is appropriate so that you can control the sprites exactly the way you want.  But sometimes it would be nice to have a sprite do something specific repeatedly or in a specific sequence of actions, without having to write a bunch of boilerplate code to make it work.

Well then, welcome to Actions in C2D.  Actions provide a great way to manipulate the sprites in a game by performing changes to one or more properties of the sprite.  C2D provides a large number of actions that can be used in your game and I debated whether to include them all in this post… since I’m still learning, I don’t have a perfect understanding of how they all work as I haven’t used them all yet. :)  However, I haven’t been able to find a lot of good references on the internet that provide a decent description of how they work (though most are reasonably obvious), so I thought I’d do my best to list them all here for reference.  If you notice something amiss here, any actions that I’ve missed, or suggestions for improvement, drop me a comment.

With that said, there are two basic types of actions:

  • Instant – The action is performed immediately on the sprite.  The following list shows the instant actions available in C2D:
    • CCFlipX – Flips the sprite on the horizontal axis.
    • CCFlipY – Flips the sprite on the vertical axis.
    • CCHide – Makes the sprite invisible on the screen.
    • CCPlace – Moves the sprite to the specified position.
    • CCRemoveSelf – Removes the sprite from it’s associated parent.
    • CCReuseGrid – Allows a grid to be reused a specified number of times (not sure how this is used??)
    • CCShow – Makes the sprite visible on the screen.
    • CCStopGrid – Stops an effect being executed on a sprite.
    • CCToggleVisibility – Toggles the visible state of the sprite.
  • Interval – The action is performed over a period of time on the sprite.  Also, almost all interval actions have a Reverse method that lets you reverse the action.  The following list shows the interval actions available in C2D:
    • CCAnimate – Animates a sprite using the associated sprite frames.
    • CCBezierBy – Moves a sprite in a bezier curve relative to the sprite’s current position.
    • CCBezierTo – Moves a sprite in a bezier curve at a fixed starting and ending position on the screen.
    • CCBlink – Toggles the visibility of a sprite off and on to flash it a specified number of times on the screen.
    • CCCardinalSplineBy – Moves a sprite in a curved motion based on a specified tension and series of control points relative to the sprite’s current position.  Microsoft has a decent description of Cardinal Splines, though their tension values are backwards vs. C2D (in C2D, 0 = smooth curve, 1 = straight line).
    • CCCardinalSplineTo – Moves a sprite in a curved motion based on a specified tension and series of fixed control points on the screen.
    • CCCatmullRomBy – Moves a sprite in a curved motion based on a series of control points relative to the sprite’s current position.  This page provides some introductory information about Catmull-Rom splines.
    • CCCatmullRomTo – Moves a sprite in a curved motion based on a series of fixed control points on the screen.
    • CCDelayTime – Waits a specified amount of time before continuing a sprite’s next action.  Useful in action sequences.
    • CCFadeIn – Adjusts the opacity of a sprite until it is completely visible on the screen.
    • CCFadeOut – Adjusts the opacity of a sprite until it is completely invisible on the screen.
    • CCFadeTo – Adjusts the opacity of a sprite to a specified level.
    • CCJumpBy – Makes a sprite jump on the screen by a specified amount, amplitude, and number of times relative to the sprite’s current position.
    • CCJumpTo – Makes a sprite jump on the screen to a specified position by a specified amount, amplitude, and number of times.
    • CCMoveBy – Moves a sprite by a specified amount on the screen relative to the sprite’s current position.
    • CCMoveTo – Moves a sprite to a specified position on the screen.
    • CCReverseTime -
    • CCRotateBy – Rotates a sprite by a specified number of degrees relative to the sprite’s current position.
    • CCRotateTo – Rotates a sprite a specified number of degrees on the screen.
    • CCScaleBy – Adjusts the size of a sprite by a specified amount relative to the sprite’s current size.  Values: 1 = original size, < 1 = smaller, > 1 = larger
    • CCScaleTo – Adjusts the size of a sprite to a specified amount.
    • CCSkewBy – Adjusts the horizontal and/or vertical angle of the sprite by a specified amount relative to the sprite’s current angle.
    • CCSkewTo – Adjusts the horizontal and/or vertical angle of the sprite to the specified amount.
    • CCTargetedAction – Applies an action to the specified target sprite.
    • CCTintBy – Adjusts the tint of a sprite by a specified RGB amount relative to the sprite’s current color.
    • CCTintTo – Adjusts the tint of a sprite to a specified RGB value.

C2D also provides a special set of composite interval actions called Easing actions, which modify the speed of the specified action while not altering the total running time (e.g. if an action should run in 2 seconds, it will continue to run in 2 seconds but it’s acceleration will be altered).  These actions come in three flavors:

  • In – The acceleration happens at the beginning of the action.
  • Out – The acceleration happens at the end of the action.
  • InOut – The acceleration happens at the beginning and end of the action.

These easing actions can be applied to movement, rotation, skewing, etc.  C2D provides the following easing actions:

  • CCEaseBackIn – Moves a sprite slightly backwards at the beginning of the action.
  • CCEaseBackInOut – Moves a sprite slightly backwards at the beginning and end of the action.
  • CCEaseBackOut – Moves a sprite slightly backwards at the end of the action.
  • CCEaseBounceIn – Moves a sprite with a bouncing motion at the beginning of the action.
  • CCEaseBounceInOut – Moves a sprite with a bouncing motion at the beginning and end of the action.
  • CCEaseBounceOut – Moves a sprite with a bouncing motion at the end of the action.
  • CCEaseCustom – Moves a sprite using a custom function.
  • CCEaseElasticIn – Moves a sprite in an elastic motion at the beginning of the action.
  • CCEaseElasticInOut – Moves a sprite in an elastic motion at the beginning and end of the action.
  • CCEaseElasticOut – Moves a sprite in an elastic motion at the end of the action.
  • CCEaseExponentialIn – Moves a sprite slowly at the beginning of the action, then with increasing speed.
  • CCEaseExponentialInOut – Moves a sprite slowly at the beginning and end of the action, with increasing speed in the middle.
  • CCEaseExponentialOut – Moves a sprite slowly at the end of the action, with increased speed at the beginning.
  • CCEaseIn – Moves a sprite slowly over a specified duration at the beginning of the action.
  • CCEaseInOut – Moves a sprite slowly over a specified duration at the beginning and end of the action.
  • CCEaseOut – Moves a sprite slowly over a specified duration at the end of the action.
  • CCEaseSineIn – Moves a sprite in a yo-yo motion, moving from beginning to end position and then back to beginning position.
  • CCEaseSineInOut – Moves a sprite slowly from beginning to end of the action.
  • CCEaseSineOut – Moves a sprite to the ending position, reverses to move beyond the beginning position by the same distance, then ends at the beginning position.

Using the basic actions in C2D can help simplify the coding in your game a good bit.  But where actions really shine in C2D is the ability to execute groups of actions in various ways, allowing you to do some wicked cool stuff.  The following special actions exist for this purpose:

  • CCParallel – Executes several actions at the same time.  Appears identical to CCSpawn below, which is the standard cocos2d method of running actions in parallel.  From what I can tell, this class appears to be exclusive to Cocos2d-XNA.
  • CCRepeat – Repeats an action a specified number of times.
  • CCRepeatForever – Repeats the action indefinitely.
  • CCSequence – Executes a series of actions one after another.
  • CCSpawn – Executes several actions at the same time.

Using the above actions, you can accomplish quite a number of things in your game with ease and simplicity that would otherwise take you some considerable time to implement yourself.  Also, if you’d like to write your own custom actions, then you can inherit from the appropriate base class and code away, so the possibilities are nearly endless.  The original cocos2d Programming Guide has a section about creating custom actions, which you should be able to translate over to C2D without too much difficulty.

I created a new project called Basic Actions in my Cocos2d-XNA-Tutorials solution on GitHub that explores some of the actions listed above.  It should be enough to give you a good idea on how to use actions and explore the ones I didn’t implement in the project.

Well, that’s about it for this post… it took several iterations to get through as I couldn’t get it all churned out in one sitting.  Hopefully you find it helpful.  Happy proggy.

Cocos2D-XNA Learning References

It just occurred to me today that before I got too far in my natterings about Cocos2D-XNA, it would probably be handy to list in one place the references I’ve been using online to learn the framework.  These are a combination of resources from the other platforms for cocos2d, so you’ll need your Python, Objective-C & C++ translation hats on as there aren’t many C# examples out there yet.  If you’ve found some good resources online, drop me a comment and I’ll be happy to list them here.

  • Cocos2d-XNA Tests – Part of the Cocos2d-XNA framework from GitHub (found in the cocos2d-xna/tests folder), contains the application used to test the framework.  There’s a ton of tests here with lots of code, so this is my first stop.
  • Cocos2d-XNA Framework – The framework code (found in the cocos2d-xna/cocos2d folder) is well organized and can be educational to see what’s going on under the hood.
  • Cocos2d-XNA Discussion Forum – CodePlex Q & A forum for Cocos2d-XNA.
  • GameDevNoob Cocos2d-x Guide – An excellent starter guide for getting an overview of the cocos2d-x framework.
  • Cocos2d Programming Guide – Original framework reference in Python.
  • Cocos2d API – Original framwork API class reference in Python.
  • Cocos2d-x Developers Manual – Cocos2d-x framework manual in C++.
  • iPhone Tutorials – Ray Wenderlich has a lot of iPhone tutorials here, with a small section on using cocos2d.

Hope these help guide you down the path to Cocos2d-XNA enlightenment. :)  Happy proggy.

Cocos2D-XNA Tutorial 1: Basic Sprites

In my last post (Cocos2D-XNA Tutorial 0: Getting Started), I explained how to setup Visual Studio with Cocos2D-XNA.  Rabbit trail – as I’m tired of typing Cocos2D-XNA multiple times in my posts, it shall henceforth be referred to as C2D (XNA is implied unless otherwise noted).

Now that we have the mundane out of the way, it’s time to move on to the goodness.  I decided to start a solution on GitHub to contain several different tutorials (that’s the plan anyway), focusing on different parts of C2D as I learn it.  These projects are explorations of what I find C2D can do, so they may or may not be what would be considered “best practices” on using the framework.  If you see something that you think can be improved or would be considered “the right way” to do it (i.e. you have prior Cocos2D experience on iOS or another platform), I’d be happy to hear your suggestions.  Also, I’m using the stock C2D assemblies from the C2D Visual Studio template instead of including the framework code in the solution, mainly because I didn’t want to clutter the solution with all the framework for the check-in to GitHub.  Feel free to kill the references and add the framework projects as I showed in my previous post if you want to break through the C2D framework.

First up, I’ve created the Basic Sprites project, which is a simple project that explores some of the basic mechanics of sprites in C2D. It provides a simple background and sprite layer, allowing different operations to be performed on the sprites.  It is by no means exhaustive, but it covers a lot of the standard operations (visibility, rotation, scaling, z-order, opacity, etc.) and shows a simple structure of a C2D game (director, scene, layers). I may add to it in the future as I learn more about sprites in C2D, but it’s good enough for now.  Here’s a quick overview of the project structure:

  • BasicSpritesGame – Your main game class.  Takes care of setting up your AppDelegate class for C2D and handling input for the game.
  • AppDelegate – Your main entry point for C2D.  Takes care of initializing C2D and instantiating your initial scene object.
  • BasicSpritesScene – Creates the BackgroundLayer and BasicSpritesLayer objects and adds them to the scene.
  • BackgroundLayer – Manages the background of the game, in this case a quick and dirty rolling landscape with a road (my art skills are EPIC, aren’t they?  Yes, they aren’t. :))
  • BasicSpritesLayer – Manages the sprites in the game, containing all the methods used to manipulate them.
  • BasicSprite – Represents the sprites in the game.  It’s a subclass of CCSprite to which I added a velocity property and movement method.

Keyboard input is used to change things in the game, so have a look at the comments on the Update method of the BasicSpritesGame class for details on the key mappings and what they do.  Speaking of keyboard input, my thanks to RCIX from this StackOverflow post who shared his keyboard input class for XNA, which I lifted from the post and used in the application.  It has handy methods for all input (game pad, keyboard, mouse) and I plan to use it often.

In regard to the specifics of what the application does, I’ve commented the code pretty heavily, so I’ll let it do the talking.  A screenshot of the application is shown below.

BasicSpritesScreenshot

Well, that’s about it for this post, hopefully you found it useful.  Happy proggy.

Cocos2D-XNA Tutorial 0: Getting Started

This is the first post in a series (at least that’s the plan) on learning to use the Cocos2d-XNA framework.  My goal in writing this series is two-fold: to help myself understand how to use this framework and by extension, to help others learn from my learning (and mistakes, which will probably be many, at least starting out :)).  The Cocos2D-XNA Learning References post contains a list of the references I’ve used to learn Cocos2d-XNA if you’re interested.  Well, it’s time to forge ahead and see what I can do.

If you’ve never heard of Cocos2D-XNA, it is a port of the Cocos2d framework (it originated on Apple’s iOS for iPhone / iPad development) to MonoGame’s cross-platform XNA API, so you get to program in C#, XNA, and Cocos2D goodness… which I think is pretty freakin’ sweet.

To get started, we need to get our environment setup to run the coolness.  I’m going to point you to the resources I used to get setup instead of trying to detail all of that stuff here:

Once you complete the above steps, you should be able to create a test application in Visual Studio with one of the Cocos2D-XNA templates (I’m using the Windows GL template), compile it, and run it successfully… your basic Hello World! app for Cocos2D-XNA.  If you’re running into problems, go back over the steps above and make sure you didn’t miss a step.

Now, the standard template gets you setup to work on a game using the appropriate binary assemblies for Cocos2D-XNA and MonoGame, which is fine.  However, if you’re like me, I like having all the code available in my solution so when I’m debugging, I can see what’s going on under the hood.  If you’d like to do the same, here’s what I did to get that setup:

  • If you don’t already have it, install GitHub for Windows on your computer.  You can get the repositories manually from GitHub if you like, but the instructions below assume you’ve installed the Git for Windows application.
  • Open a Git Shell prompt and change to a location on your drive where you want to store the repositories (e.g. C:\GitRepos).
  • Head over to the Cocos2D-XNA GitHub page and have a look at the Readme.md at the bottom of the page for instructions on how to install the source code properly.
  • Create a new Cocos2D-XNA game project in Visual Studio.

Create New Cocos2D-XNA Project

  • Remove the box2d, cocos2d-xna, Lidgren.Network, and MonoGame.Framework references from your  project.

Cocos2D-XNA Solution References

  •  Add the box2d, cocos2d-xna, Lidgren.Network, and MonoGame.Framework projects to the solution from the MonoGame and Cocos2D-XNA repositories.  There are several projects for MonoGame and Cocos2D-XNA, so you need to select the correct project type based on the platform you’re targeting.  For example, if you made a Windows GL Cocos2D-XNA game, you would add the following projects to your solution:
<GitRepoLocation>MonoGameMonoGame.FrameworkMonoGame.Framework.WindowsGL.proj
<GitRepoLocation>MonoGameThirdPartyLidgren.NetworkLidgren.Network.Windows.csproj
<GitRepoLocation>cocos2d-xnabox2dbox2d.WindowsGL.csproj
<GitRepoLocation>cocos2d-xnacocos2dcocos2d.WindowsGL.csproj

Add VS Project Dialog

  • In your game project, add a project reference to the box2d, cocos2d-xna, Lidgren.Network, and MonoGame.Framework projects.

Add Project References

  • Compile your solution and verify that it builds successfully.  If so, you should be all set.  If not, make sure you added the references in the order shown above.  I initially had an issue with the Cocos2D-XNA project generating a ton of errors that made no sense, like it was missing the MonoGame reference even though it was pointing to the correct location.  I removed the project reference and added it back, and poof… no more errors.  So I’m thinking it was an ordering problem of how I added the projects and/or project references.

After getting all that setup, I was able to break through my game code, as well as all the applicable framework code.  Now I’m ready to get going on some game development with Cocos2D-XNA and hopefully you are too.  Happy proggy.

 

RPG Musings and Prototypes and Settling on a Game Engine

Well, my first meaningful post comes a little over two months since my initial kickoff post… as I said before, I’m not much of a blogger. :D  Oh well, I’ll see if I can change that yet.

I’ve always wanted to write a role-playing game as it’s one of my favorite genres to play, but pulling it off is a pretty major undertaking as there are a lot of elements to pull together.  However, I’m approaching it with a positive attitude and the mindset of adding a little at a time until I’ve got something usable, perhaps even fun… as all good games should be. :)

I started fleshing out some design ideas several months ago, so I dusted them off and looked for a good starting point.  I settled on map generation, as I’d like my game to have a new, randomized world each time you play it… but also playable again if you like it.  Basically patterned after Minecraft with an entered seed that is fed to your psuedo-random number generator to produce your world.

So the last couple weeks have been spent researching ways to generate interesting world maps (city and dungeon maps will trail along too at some point), and I’ve really had some fun learning some different ideas on map generation.  I wanted something random but not just a bunch of garbage in little clumps, which is what you get with a true random approach.  I wanted land features that were “random” but also natural looking.  After perusing the Internets for several days, I decided to use a Simplex Noise algorithm to generate my world map.  Simplex Noise is the big brother to Perlin Noise, both of which were written by a smart chap named Ken Perlin.  I examined the Word according to Brother Stefan Gustavson on the subject (you can find a link to the paper at the bottom of the Simplex Noise wiki page) and I must say, it gets pretty deep into the math bushes… I was never a math genius and I don’t pretend to understand all the math behind the generation, but the general concepts made sense.  I found a Java implementation that I rolled over to C# to generate a Simplex Noise and it works pretty good.  I had some fun putting together that prototype as it produced some great results for me… I spent several hours just tinkering with it and looking at the generations.  My prototype is a quick & dirty WinForms app that basically uses the generated noise as an elevation map and I assigned terrain types/colors according to ranges in the elevation.  I posted my prototype on GitHub for anyone interested in seeing what it can do – https://github.com/ricke44654/SimplexNoise.

After playing with that for a while, I decided to refine it to use two noises – one for elevation and another for moisture, then combine the two to make more interesting landscapes.  I then wanted to visualize the world close up with by “walking around” on the map, so I started to make a rudimentary viewer in my app with GDI+.  After a little work, I had something going but wasn’t at all satisfied with the performance… so I decided it was time to start looking for a game engine.  One thing I wanted was to have my game run on multiple platforms, mainly a PC and an Android device.  I had dabbled with XNA back in the day and thought it was solid, but didn’t want to be tied to Windows specifically.  A couple months ago, I stumbled on to MonoGame through my Xamarin development at work and it looks pretty sweet – an open source multi-platform XNA framework with just the platforms I was looking for and the ability to leverage the numerous XNA resources that exist out in the wild already… ching.  But that still leaves some heavy lifting on the part of game engine mechanics, such as movement, collision detection, screen management, etc.

Enter Cocos2d-XNA, an open source 2D/3D game development framework built for XNA but supports multiple platforms through MonoGame as XNA is on it’s way out.  I had seen some variants of Cocos2d around but nothing that I could really leverage in C#… until now. :)  My hats off to the chaps who put all this stuff together, it is some cool business.  With that said, it has been a little challenging trying to learn how to marry these three technologies together over the last few days, especially the Cocos2d-XNA goodness which is very light in the way of documentation… they freely admit as much on their site and are working to improve it.  No flames, boys… I know docs often come in last in the development cycle, I’m sure they’ll get better, at least I hope so. ;)  In the mean time, after getting frustrated with getting a basic running app going for a couple days, I looked up a book on Cocos2d programming (it originated on Apple iOS) called Learning Cocos2D: A Hands-On Guide to Building iOS Games with Cocos2D, Box2D, and Chipmunk.  As I have access to Safari Online (which rocks!), I started reading immediately.  The book lays out a pretty good introduction so far (I’m on Chapter 2) on Cocos2d architecture, it’s amazing how much you can do with just a few lines of code.  I don’t know Objective-C or the iOS/XCode platform, but so far I haven’t had any trouble translating the examples into C# Cocos2d-XNA goodness, so it’s all good right now.  My plan is to get up to speed on Cocos2d with this book, then leverage that learning to dig into my game.

All in all, it’s been a fun couple of weeks learning some new programming magic.  In a future post, I’m planning to detail my navigation through the XNA / MonoGame / Cocos2d-XNA jungle on how I got my code up and running so maybe it can help anyone else who wants to pursue this course.  But right now, it’s time to go to bed… 5:30am is going to come all too soon.  Happy proggy.