PushButton Engine Lesson # 4: Adding Control to a Custom Component



    In today's tutorial, we’ll look at how you can create keyboard-driven objects in the PushButton Engine . If you are just starting out with the PushButton Engine (PBE) , then you might find it helpful to read lesson # 1 , lesson # 2, and lesson # 3 from a series of tutorials about PBE . Also, you can always read the lessons in the original articles on the official website .

    Keyboard control

    “Human beings, vegetables or cosmic dust, we all dance to the mysterious melody played by an invisible musician from a distance.” - Albert Einstein.

    The purpose of this lesson is to learn how to create custom components that use keyboards to move a simple figure across the screen.

    Like previous lessons, this lesson consists of a series of steps: small gaps that will focus on achieving small goals. This approach will speed up the understanding of the PusButton Engine .

    This lesson will be useful if you are just starting to learn PBE . But despite this, it is not necessary that you are new to programming.

    - Files to start the lesson
    - Introduction to the lesson
    - Creating a component
    - Checking the results of work
    - Conclusion

    Files to start the lesson

    To start learning the lesson, you can download the starter project and use it as a base for completing the lesson:

    A kit to start learning the lesson

    If you compile a .swf file from the starter kit for the lesson, you should have a blue circle in the center of the screen.

    The source files for the completed lesson will be available at the end of the article.

    Lesson introduction

    In the previous lesson, we learned how to create a simple controller component that controls a character based on a behavioral model. Now, we will add keystrokes that will add movements controlled by the player.

    In order to streamline user input, PBE provides the PBE.isKeyDown () method , which checks to see if any button is pressed.

    For more complex input settings, such as actions on keyboard shortcuts or sending special events for buttons, PBE provides the classes InputManager and InputMap. These classes provide more “strong” functionality, but, usually, they are not needed when creating simple games. In this lesson we will not discuss them.

    Component Creation

    As in the previous lesson, we will again create a simple scene with 3 simple components: a render component, a “spatial” component, and a controller component. And, again, we will create a custom component that will be inherited from the TicketComponent class , which has the ability to “update” itself on every frame.

    This new component will check if the buttons are pressed left or right, and if one of them is pressed, the component will move the object.

    The InputKey class provides the ability to work with a large number of buttons:

    // Коды кнопок могут быть получены через статические константы класса InputKey
    // Или с помощью строковых имён

    * This source code was highlighted with Source Code Highlighter.

    In the root directory of the lesson you will find a template for the HeroControllerComponent class . To add responsiveness to keyboard events, each time we call the onTick () method, we will ask PBE to check the pressed buttons, which we are interested in pressing. This can be done using the PBE.isKeyDown () method , in approximately the following way:

    // Метод isKeyDown() возвращает булево значение, которое показывает, нажата сейчас проверяемая кнопка или нет (true — да, false — нет)
    if (PBE.isKeyDown(InputKey.SPACE))
        // Реакция на нажатие клавиши
        Logger.print(this, "Hey, cheer up!");

    * This source code was highlighted with Source Code Highlighter.

    Depending on which key is currently pressed, we change the position of the spatial component. As in the previous lesson, we will receive a link to the spatial component position variable through the PropertyReference class , make changes in accordance with our rules and set a new value for this variable.

    The rules according to which we will change the position of the object:

    1) If the "Right" button is pressed: move the object to the right
    2) If the "Left" button is pressed: move the object to the left
    3) If the object is beyond the right edge of the flash drive: return the object to the right edge of the flash drive
    4) If the object is beyond the left edge of the flash drive: return the object to the left edge of the flash drive

    Now that we’ve figured out how things should work, we can implement this in code. Change the HeroControllerComponent class to match the code below:

    File path: /src/HeroControllerComponent.as
        import com.pblabs.engine.PBE;
        import com.pblabs.engine.components.TickedComponent;
        import com.pblabs.engine.core.InputKey;
        import com.pblabs.engine.entity.PropertyReference;

        import flash.geom.Point;
         * Класс, который умеет «обновлять» себя на каждом кадре с помощью метода onTick()
        public class HeroControllerComponent extends TickedComponent
            // Переменная, которая будет сохранять ссылку на положение объекта
            public var positionReference:PropertyReference;
            public function HeroControllerComponent()
             * Функция, которая будет вызываться на каждом кадре.
             * @param    deltaTime время, прошедшее с предыдущего обновления.
            public override function onTick(deltaTime:Number):void
                // Получаем ссылку на переменную положения объекта
                var position:Point = owner.getProperty(positionReference);
                // Проверяем, нажата ли кнопка «Вправо»
                if (PBE.isKeyDown(InputKey.RIGHT))
                    // Передвигаем объект вправо
                    position.x += 15;
                // Проверяем, нажата ли кнопка «Влево»
                if (PBE.isKeyDown(InputKey.LEFT))
                    // Передвигаем объект влево
                    position.x -= 15;
                // Если объект выходит вправо за пределы флешки
                if (position.x > 375)
                    // Возвращаем объект к правому краю
                    position.x = 375;
                // Если объект выходит влево за пределы флешки
                }else if (position.x < -375)
                    // Возвращаем объект к левому краю
                    position.x = -375;
                // Устанавливаем положение объекта в соответствии с изменениями
                owner.setProperty(positionReference, position);

    * This source code was highlighted with Source Code Highlighter.

    Checking the results of work

    After you compile the flash drive, you should see a .swf file, the contents of which should look like the screenshot below:



    Congratulations, you have completed Lesson 4 and learned how to add user input reactions.

    You can download all the files that were used in the lesson from the link below.

    Archive with lesson sources

    Also popular now: