17 min read

In this article by Richard Sneyd, the author of Stencyl Essentials, we will learn about Stencyl’s signature visual programming interface to create logic and interaction in our game. We create this logic using a WYSIWYG (What You See Is What You Get) block snapping interface. By the end of this article, you will have the Player Character whizzing down the screen, in pursuit of a zigzagging air balloon! Some of the things we will learn to do in this article are as follows:

  • Create Actor Behaviors, and attach them to Actor Types.
  • Add Events to our Behaviors.
  • Use If blocks to create branching, conditional logic to handle various states within our game.
  • Accept and react to input from the player.
  • Apply physical forces to Actors in real-time.

One of the great things about this visual approach to programming is that it largely removes the unpleasantness of dealing with syntax (the rules of the programming language), and the inevitable errors that come with it, when we’re creating logic for our game. That frees us to focus on the things that matter most in our games: smooth, well wrought game mechanics and enjoyable, well crafted game-play.

(For more resources related to this topic, see here.)

The Player Handler

The first behavior we are going to create is the Player Handler. This behavior will be attached to the Player Character (PC), which exists in the form of the Cowboy Actor Type. This behavior will be used to handle much of the game logic, and will process the lion’s share of player input.

Creating a new Actor Behavior

It’s time to create our very first behavior! Go to the Dashboard, under the LOGIC heading, select Actor Behaviors:

Stencyl Essentials

Click on This game contains no Logic. Click here to create one. to add your first behavior. You should see the Create New… window appear:

Stencyl Essentials

Enter the Name Player Handler, as shown in the previous screenshot, then click Create. You will be taken to the Behavior Designer:

Stencyl Essentials

Let’s take a moment to examine the various areas within the Behavior Designer. From left to right, as demonstrated in the previous screenshot, we have:

  • The Events Pane: Here we can add, remove, and move between events in our Behavior.
  • The Canvas: To the center of the screen, the Canvas is where we drag blocks around to click our game logic together.
  • The blocks Palette: This is where we can find any and all of the various logic blocks that Stencyl has on offer. Simply browse to your category of choice, then click and drag the block onto the Canvas to configure it.

Follow these steps:

  1. Click the Add Event button, which can be found at the very top of the Events Pane.
  2. In the menu that ensues, browse to Basics and click When Updating:

    Stencyl Essentials

You will notice that we now have an Event in our Events Pane, called Updated, along with a block called always on our Canvas. In Stencyl events lingo, always is synonymous with When Updating:

Stencyl Essentials

Since this is the only event in our Behavior at this time, it will be selected by default. The always block (yellow with a red flag) is where we put the game logic that needs to be checked on a constant basis, for every update of the game loop (this will be commensurate with the framerate at runtime, around 60fps, depending on the game performance and system specs). Before we proceed with the creation of our conditional logic, we must first create a few attributes.

If you have a programming background, it is easiest to understand attributes as being synonymous to local variables. Just like variables, they have a set data type, and you can retrieve or change the value of an attribute in real-time.

Creating Attributes

Switch to the Attributes context in the blocks palette:

Stencyl Essentials

There are currently no attributes associated with this behavior. Let’s add some, as we’ll need them to store important information of various types which we’ll be using later on to craft the game mechanics. Click on the Create an Attribute button:

Stencyl Essentials

In the Create an Attribute… window that appears, enter the Name Target Actor, set Type to Actor, check Hidden?, and press OK:

Stencyl Essentials

Congratulations! If you look at the lower half of the blocks palette, you will see that you have added your first attribute, Target Actor, of type Actors, and it is now available for use in our code.

Stencyl Essentials

Next, let’s add five Boolean attributes. A Boolean is a special kind of attribute that can be set to either true, or false. Those are the only two values it can accept. First, let’s create the Can Be Hurt Boolean:

  1. Click Create an Attribute….
  2. Enter the Name Can Be Hurt.
  3. Change the Type to Boolean.
  4. Check Hidden?.
  5. Press OK to commit and add the attribute to the behavior.
  6. Repeat steps 1 through 5 for the remaining four Boolean attributes to be added, each time substituting the appropriate name:
    •     Can Switch Anim
    •     Draw Lasso
    •     Lasso Back
    •     Mouse Over

If you have done this correctly, you should now see six attributes in your attributes list – one under Actor, and five under Boolean – as shown in the following screenshot:

Stencyl Essentials

Now let’s follow the same process to further create seven attributes; only this time, we’ll set the Type for all of them to Number. The Name for each one will be:

  • Health (Set to Hidden?).
  • Impact Force (Set to Hidden?).
  • Lasso Distance (Set to Hidden?).
  • Max Health (Don’t set to Hidden?).
  • Turn Force (Don’t set to Hidden?).
  • X Point (Set to Hidden?).
  • Y Point (Set to Hidden?).

If all goes well, you should see your list of attributes update accordingly:

Stencyl Essentials

We will add just one additional attribute. Click the Create an Attribute… button again:

  1. Name it Mouse State.
  2. Change its Type to Text.
  3. Do not hide this attribute.
  4. Click OK to commit and add the attribute to your behavior.

Excellent work, at this point, you have created all of the attributes you will need for the Player Handler behavior!

Custom events

We need to create a few custom events in order to complete the code for this game prototype. For programmers, custom events are like functions that don’t accept parameters. You simply trigger them at will to execute a reusable bunch of code. To accept parameters, you must create a custom block:

  1. Click Add Event.
  2. Browse to Advanced..
  3. Select Custom Event:

    Stencyl Essentials

You will see that a second event, simply called Custom Event, has been added to our list of events:

Stencyl Essentials

Now, double-click on the Custom Event in the events stack to change its label to Obj Click Check (For readability purposes, this does not affect the event’s name in code, and is completely ignored by Stencyl):

Stencyl Essentials

Now, let’s set the name as it will be used in code. Click between When and happens, and insert the name ObjectClickCheck:

Stencyl Essentials

From now on, whenever we want to call this custom event in our code, we will refer to it as ObjectClickCheck. Go back to the When Updating event by selecting it from the events stack on the left. We are going to add a special block to this event, which calls the custom event we created just a moment ago:

  1. In the blocks palette, go to Behaviour | Triggers | For Actor, then click and drag the highlighted block onto the canvas:

    Stencyl Essentials

  2. Drop the selected block inside of the Always block, and fill in the fields as shown (please note that I have deliberately excluded the space between Player and Handler in the behavior name, so as to demonstrate the debugging workflow. This will be corrected in a later part of the article):

    Stencyl Essentials

Now, ObjectClickCheck will be executed for every iteration of the game loop! It is usually a good practice to split up your code like this, rather than having it all in one really long event. That would be confusing, and terribly hard to sift through when behaviors become more complex!

Here is a chance to assess what you have learnt from this article thus far. We will create a second custom event; see if you can achieve this goal using only the skeleton guide mentioned next. If you struggle, simply refer back to the detailed steps we followed for the ObjectClickCheck event:

  1. Click Add Event | Advanced | Custom Event. A new event will appear at the bottom of the events pane.
  2. Double Click on the event in the events pane to change its label to Handle Dir Clicks for readability purposes.
  3. Between When and happens, enter the name HandleDirectionClicks. This is the handle we will use to refer to this event in code.
  4. Go back to the Updated event, right click on the Trigger event in behavior for self block that is already in the always block, and select copy from the menu.
  5. Right-click anywhere on the canvas and select paste from the menu to create an exact duplicate of the block.
  6. Change the event being triggered from ObjectClickCheck to HandleDirectionClicks. Keep the value PlayerHandler for the behavior field.
  7. Drag and drop the new block so that it sits immediately under the original.

Holding Alt on the keyboard, and clicking and dragging on a block, creates a duplicate of that block.

Were you successful? If so, you should see these changes and additions in your behavior (note that the order of the events in the events pane does not affect the game logic, or the order in which code is executed).

Stencyl Essentials

Learning to create and utilize custom events in Stencyl is a huge step towards mastering the tool, so congratulations on having come this far!

Testing and debugging

As with all fields of programming and software development, it is important to periodically and iteratively test your code. It’s much easier to catch and repair mistakes this way. On that note, let’s test the code we’ve written so far, using print blocks. Browse to and select Flow | Debug | print from the blocks palette:

Stencyl Essentials

Now, drag a copy of this block into both of your custom events, snapping it neatly into the when happens blocks as you do so.

  • For the ObjectClickCheck event, type Object Click Detected into the print block
  • For the HandleDirectionClicks event, type Directional Click Detected into the print block.

We are almost ready to test our code. Since this is an Actor Behavior, however, and we have not yet attached it to our Cowboy actor, nothing would happen yet if we ran the code. We must also add an instance of the Cowboy actor to our scene:

  1. Click the Attach to Actor Type button to the top right of the blocks palette:

    Stencyl Essentials

  2. Choose the Cowboy Actor from the ensuing list, and click OK to commit.
  3. Go back to the Dashboard, and open up the Level 1 scene.
  4. In the Palette to the right, switch from Tiles to Actors, and select the Cowboy actor:

    Stencyl Essentials

  5. Ensure Layer 0 is selected (as actors cannot be placed on background layers). Click on the canvas to place an instance of the actor in the scene, then click on the Inspector, and change the x and y Scale of the actor to 0.8:

    Stencyl Essentials

Well done! You’ve just added your first behavior to an Actor Type, and added your first Actor Instance to a scene! We are now ready to test our code. First, Click the Log Viewer button on the toolbar:

Stencyl Essentials

This will launch the Log Viewer. The Log Viewer will open up, at which point we need only set Platform to Flash (Player), and click the Test Game Button to compile and execute our code:

Stencyl Essentials

After a few moments, if you have followed all of the steps correctly, you will see that the game windows opens on the screen and a number of events appear on the Log Viewer. However, none of these events have anything to do with the print blocks we added to our custom events. Hence, something has gone wrong, and must be debugged. What could it be? Well, since the blocks simply are not executing, it’s likely a typo of some kind. Let’s look at the Player Handler again, and you’ll see that within the Updated event, we’ve referred to the behavior name as PlayerHandler in both trigger event blocks, with no space inserted between the words Player and Handler:

Stencyl Essentials

Update both of these fields to Player Handler, and be sure to include the space this time, so that it looks like the following (To avoid a recurrence of this error, you may wish to use the dropdown menu by clicking the downwards pointing grey arrow, then selecting Behavior Names to choose your behavior from a comprehensive list):

Stencyl Essentials

Great work! You have successfully completed your first bit of debugging in Stencyl. Click the Test Game button again. After the game window has opened, if you scroll down to the bottom of the Log Viewer, you should see the following events piling up:

Stencyl Essentials

These INFO events are being triggered by the print blocks we inserted into our custom events, and prove that our code is now working. Excellent job! Let’s move on to a new Actor; prepare to meet Dastardly Dan!

Adding the Balloon

Let’s add the balloon actor to our game, and insert it into Level 1:

  1. Go to the Dashboard, and select Actor Types from the RESOURCES menu.
  2. Press Click here to create a new Actor Type.
  3. Name it Balloon, and click Create.
  4. Click on This Actor Type contains no animations. Click here to add an animation.
  5. Change the text in the Name field to Default.
  6. Un-check looping?.
  7. Press the Click here to add a frame. button. The Import Frame from Image Strip window appears.
  8. Change the Scale to 4x.
  9. Click Choose Image… then browse to Game AssetsGraphicsActor Animations and select Balloon.png.
  10. Keep Columns and Rows set to 1, and click Add to commit this frame to the animation.
  11. All animations are created with a box collision shape by default. In actuality, the Balloon actor requires no collisions at all, so let’s remove it. Go to the Collision context, select the Default box, and press Delete on the keyboard:

    Stencyl Essentials

The Balloon Actor Type is now free of collision shapes, and hence will not interact physically with other elements of our game levels. Next, switch to the Physics context:

Stencyl Essentials

Set the following attributes:

  1. Set What Kind of Actor Type? to Normal.
  2. Set Can Rotate? To No. This will disable all rotational physical forces and interactions. We can still rotate the actor by setting its rotation directly in the code, however.
  3. Set Affected by Gravity? to No. We will be handling the downward trajectory of this actor ourselves, without using the gravity implemented by the physics engine.

Just before we add this new actor to Level 1, let’s add a behavior or two. Switch to the Behaviors context:

Stencyl Essentials

Then, follow these steps:

  1. This Actor Type currently has no attached behaviors. Click Add Behavior, at the bottom left hand corner of the screen:

    Stencyl Essentials

  2. Under FROM YOUR LIBRARY, go to the Motion category, and select Always Simulate. The Always Simulate behavior will make this actor operational, even if it is not on the screen, which is a desirable result in this case. It also prevents Stencyl from deleting the actor when it leaves the scene, which it would automatically do in an effort to conserve memory, if we did not explicitly dictate otherwise. Click Choose to add it to the behaviors list for this Actor Type. You should see it appear in the list:

    Stencyl Essentials

  3. Click Add Behavior again.
  4. This time, under FROM YOUR LIBRARY, go the Motion category once more, and this time select Wave Motion (you’ll have to scroll down the list to see it). Click Choose to add it to the behavior stack. You should see it sitting under the Always Simulate behavior:

    Stencyl Essentials

Configuring prefab behaviors

Prefab behaviors (also called shipped behaviors) enable us to implement some common functionality, without reinventing the wheel, so to speak. The great thing about these prefab behaviors, which can be found in the behavior library, is that they can be used as templates, and modified at will. Let’s learn how to add and modify a couple of these prefab behaviors now.

Some prefab behaviors have exposed attributes which can be configured to suit the needs of the project. The Wave Motion behavior is one such example. Select it from the stack, and configure the attributes as follows:

  1. Set Direction to Horizontal from the dropdown menu.
  2. Set Start Speed to 5.
  3. Set Amplitude to 64.
  4. Set Wavelength to 128.

Fantastic! Now let’s add an Instance of the Balloon actor to Level 1:

  1. Click the Add to Scene button at the top right corner of your view. Select the Level 1 scene.
  2. Select the Balloon.
  3. Click on the canvas, below the Cowboy actor, to place an instance of the Balloon in the scene:

    Stencyl Essentials

Modifying prefab behaviors

Before we test the game one last time, we must quickly add a prefab behavior to the Cowboy Actor Type, modifying it slightly to suit the needs of this game (for instance, we will need to create an offset value for the y axis, so the PC is not always at the centre of the screen):

  1. Go to the Dashboard, and double click on the Cowboy from the Actor Types list.
  2. Switch to the Behavior Context.
  3. Click Add Behavior, as you did previously when adding prefab behaviors to the Balloon Actor Type.
  4. This time, under FROM YOUR LIBRARY, go to the Game category, and select Camera Follow. As the name suggests, this is a simple behavior that makes the camera follow the actor it is attached to. Click Choose to commit this behavior to the stack, and you should see this:

    Stencyl Essentials

  5. Click the Edit Behavior button, and it will open up in the Behavior Designer:

    Stencyl Essentials

  6. In the Behavior Designer, towards the bottom right corner of the screen, click on the Attributes tab:

    Stencyl Essentials

  7. Once clicked, you will see a list of all the attributes in this behavior appear in the previous window. Click the Add Attribute button:

    Stencyl Essentials

    Perform the following steps:

    1. Set the Name to Y Offset.
    2. Change the Type to Number.
    3. Leave the attribute unhidden.
    4. Click OK to commit new attribute to the attribute stack:

      Stencyl Essentials

  8. We must modify the set IntendedCameraY block in both the Created and the Updated events:

    Stencyl Essentials

  9. Holding Shift, click and drag the set IntendedCameraY block out onto the canvas by itself:

    Stencyl Essentials

  10. Drag the y-center of Self block out like the following:

    Stencyl Essentials

  11. Click the little downward pointing grey arrow at the right of the empty field in the set intendedCameraY block , and browse to Math | Arithmetic | Addition block:

    Stencyl Essentials

  12. Drag the y-center of Self block into the left hand field of the Add block:

    Stencyl Essentials

  13. Next, click the small downward pointing grey arrow to the right of the right hand field of the Addition block to bring up the same menu as before. This time, browse to Attributes, and select Y Offset:

    Stencyl Essentials

  14. Now, right click on the whole block, and select Copy (this will copy it to the clipboard), then simply drag it back into its original position, just underneath set intendedCameraX:

    Stencyl Essentials

  15. Switch to the Updated Event from the events pane on the left, hold Shift, then click and drag set intendedCameraY out of the Always block and drop it in the trash can, as you won’t need it anymore. Right-click and select Paste to place a copy of the new block configuration you copied to the clipboard earlier:

    Stencyl Essentials

  16. Click and drag the pasted block so that it appears just underneath the set intendedCameraX block, and save your changes:

    Stencyl Essentials

Testing the changes

Go back to the Cowboy Actor Type, and open the Behavior context; click File | Reload Document (Ctrl-R or Cmd-R) to update all the changes. You should see a new configurable attribute for the Camera Follow Behavior, called Y Offset. Set its value to 70:

Stencyl Essentials

Excellent! Now go back to the Dashboard and perform the following:

  1. Open up Level 1 again.
  2. Under Physics, set Gravity (Vertical) to 8.0.
  3. Click Test Game, and after a few moments, a new game window should appear. At this stage, what you should see is the Cowboy shooting down the hill with the camera following him, and the Balloon floating around above him.

Summary

In this article, we learned the basics of creating behaviors, adding and setting Attributes of various types, adding and modifying prefab behaviors, and even some rudimentary testing and debugging. Give yourself a pat on the back; you’ve learned a lot so far!

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here