Главная » Просмотр файлов » Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008

Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 16

Файл №779888 Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (Symbian Books) 16 страницаWiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888) страница 162018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 16)

This class is similar to the periodic timer,except that it provides a function to restore timer accuracy if it getsout of synchronization with the system clock. The CHeartBeat classaccommodates the delay by calling separate event-handling methodsdepending on whether it ran accurately, that is, on time, or whetherit was delayed, to allow it to re-synchronize.

However, this additionalfunctionality is not usually necessary. Extremely accurate timing isn’tgenerally required because a game engine only needs to know accuratelyhow much time has elapsed since the previous frame, so, for example,the total amount of movement of a graphics object can be calculated.There is also a high resolution timer available through the CTimerclass, using the HighRes() method and specifying the interval requiredHANDLING INPUT FROM THE KEYPAD49in microseconds.

The resolution of this timer is 1 ms on phone hardware,but defaults to 5 ms on the Windows emulator, although it can be changedby modifying the TimerResolution variable in the epoc.ini emulator file. However, on Windows, there is no real-time guarantee as there ison the smartphone hardware, because the timings are subject to whateverelse is running on Windows.2.4 Handling Input from the KeypadHandling user input made by pressing keys on the phone’s keypad isquite straightforward in the Symbian OS application framework. Theapplication UI class should call CCoeAppUI::AddToStackL() whenit creates an application view to ensure that keypad input is passedautomatically to the current view. The key events can be inspected byoverriding CCoeControl::OfferKeyEventL().Note that only input from the numerical keypad and multi-way controller is passed into CCoeControl::OfferKeyEventL().

Input fromthe user’s interaction with the menu bar, toolbar, or softkeys, is passedseparately to the HandleCommandL() method of the application UIclass for S60. In UIQ, the application view handles in-command input.This is because a command can be located on a softkey, in a toolbar, orin a menu, depending on the interaction style of the phone. To allow forthis flexibility, commands are defined in a more abstract way, rather thanbeing explicitly coded as particular GUI elements, such as menu items.For either UI platform, the input event is handled according to theassociated command, which is specified in the application’s resourcefile.

The Skeleton example demonstrates basic menu input handlingin CSkeletonAppUi::HandleCommandL() for S60 and CSkeletonUIQView::HandleCommandL() for UIQ.In the Skeleton example, the handling of the user input is decoupledfrom the actual event, by storing it in a bitmask (iKeyState) when it isreceived, and handling it when the game loop next runs by inspectingiKeyState. This approach is shown in the simplified example code, forS60, below.TKeyResponse CSkeletonAppView::OfferKeyEventL(const TKeyEvent&aKeyEvent, TEventCode aType){TKeyResponse response = EKeyWasConsumed;TUint input = 0x00000000;switch (aKeyEvent.iScanCode){case EStdKeyUpArrow: // 4-way controller upinput = KControllerUp; // 0x00000001;break;case EStdKeyDownArrow: // 4-way controller down50SYMBIAN OS GAME BASICSinput = KControllerDown; // 0x00000002;break;case EStdKeyLeftArrow: // 4-way controller leftinput = KControllerLeft; // 0x00000004;break;case EStdKeyRightArrow: // 4-way controller rightinput = KControllerRight; // 0x00000008;break;case EStdKeyDevice3: // 4-way controller centerinput = KControllerCentre;// This is the "fire ammo" key// Store the event, the loop will handle and clear itif (EEventKey == aType){iFired = ETrue;}...default:response = EKeyWasNotConsumed;// Keypress was not handledbreak;}if (EEventKeyDown == aType){// Store input to handle in the next updateiKeyState | = input; // set bitmask}else if (EEventKeyUp == aType){// Clear the inputiKeyState &= ∼input; // clear bitmask}return (response);}TKeyEvent and TEventCode are passed in as parameters to OfferKeyEventL(), and contain three important values for the key press – theevent type, scan code, and character code for the key.

Let’s discuss thesein some further detail.2.4.1 Key EventsKey events are delivered to the application by the Symbian OS windowserver (WSERV). WSERV uses a typical GUI paradigm which works wellfor controls such as text editors and list boxes. That is, when a key isheld down, it generates an initial key event, followed by a delay andthen a number of repeat key events, depending on the keypad repeat ratesetting, until it is released.There are three possible key event types. Each key press generates thethree event types in sequence:1.EEventKeyDown – generated when the key is pressed downHANDLING INPUT FROM THE KEYPAD512. EEventKey – generated after the key down event, and then regularlyas long as the key is kept down23. EEventKeyUp – generated when the key is released.The EEventKeyDown and EEventKeyUp pair of events can be usedto set a flag in the game to indicate that a particular key is being held, andthen clear it when it is released, as shown in the previous example.

Usingthis technique, the state of the relevant input keys is stored, and key repeatinformation can be ignored (the repeated input notification often doesnot work well for games, because it results in jerky motion, for example,when a user holds down a key to drive a car forward in one direction).However, it can be useful in other contexts. Since the EEventKey eventis passed repeatedly if a key is held down, it can be used for repeatingevents, such as firing ammunition every quarter second while a particularkey is held down. This is much easier and more comfortable for the playerthan needing to repeatedly press the key. The Skeleton example code,shown above, illustrates this each time a repeat event is received fromholding down the centre key of the 4-way controller.2.4.2 Key CodesEither the scan code or the character code can be used by the game todetermine which key has been pressed.

The scan code (TKeyEvent::iScanCode) simply provides information about the physical key pressed,which is usually sufficient for processing events in games, since all thatis required is information about the direction or the keypad numberpressed. The character code may change when, for example, a singlekey is pressed multiple times, depending on how the mappings and anyfront end processors are set up.

This level of detail isn’t often needed bya game, so the character code is generally ignored.A game must also be able to handle the case where two or more keysare pressed simultaneously, for example, to simulate 8-way directionalcontrol or allow for more complicated key sequences and controls. TheSkeleton example does this by storing input in a bitmask, so multiplesimultaneous key presses can be handled together by the loop.By default, pressing multiple keys simultaneously is not possible;the event from the first key to be pressed is received and others arediscarded while it is held down.

This is called key blocking. However,the application UI can call CAknAppUi::SetKeyBlockMode() on2RWsSession::GetKeyboardRepeatRate() can be used to determine the repeatinterval and it can be modified by calling RWsSession::SetKeyboardRepeatRate().52SYMBIAN OS GAME BASICSS60 to disable key blocking for the application and accept multiple keypress events. However, this is not possible on UIQ.One other thing to note about input is that phone keypads have alimited number of keys, which are not always ergonomic for game play.The variety of layouts and the size limitations need to be considered whendesigning a game, and ideally should be configurable, through a menuoption, so the user can choose their own, according to their preferenceand the smartphone model in question.

It is also a good idea to designgames to always allow for one-handed play, since some devices are toosmall for game playing to be comfortable using both hands. However,other devices are suited to two-handed game playing, particularly whenthey can be held in landscape orientation, such as the Nokia N95 or theNokia N81. The instance where phones can be used in both portrait andlandscape orientations, and the game supports each mode, is anothergood reason for allowing the game keys to be configurable. The user canset different key configurations for gameplay depending on the orientationof the phone.2.5 Handling Input from the ScreenSome UIQ smartphones, such as the Sony Ericsson P1i, support touchscreen input, which can be used to add another mode of user interactionto a game. Screen events can be detected and handled in much the sameway as keypad input, by overriding CCoeControl::HandlePointerEventL() as shown below.

In the example given, to capture events thatoccur in the close vicinity of a particular point on the screen, an area ofthe screen is constructed, ten pixels square, and centered on the pointin question. When a pointer-down screen event occurs, if the point atwhich the tap occurred lies within the square, the user input is stored ina bitmask in the same way as for a key press.void CSkeletonUIQView::HandlePointerEventL(const TPointerEvent&aPointerEvent){if (TPointerEvent::EButton1Up == aPointerEvent.iType){// Pointer up events clear the screeniKeyState = 0x00000000; // clear all previous selections}else if (TPointerEvent::EButton1Down == aPointerEvent.iType){TRect drawRect( Rect());TInt width = drawRect.Width();TInt height = drawRect.Height();TPoint offset(10,10); // 10x10 square around the screen positionTPoint k1(width/4, height/2);HANDLING INPUT FROM THE SCREEN53TRect rect1(TPoint(k1-offset), TPoint(k1+offset));if (rect1.Contains(aPointerEvent.iPosition)){iKeyState | = KKey1;return; // stored the event, so return}TPoint k2(width/2, height/2);TRect rect2(TPoint(k2-offset), TPoint(k2+offset));if (rect2.Contains(aPointerEvent.iPosition)){iKeyState | = KKey2;return; // stored the event, so return}...

// Other numbers similarly inspected}// Pointer events for other areas of the screen are ignored// Pass them to the base classCCoeControl::HandlePointerEventL(aPointerEvent);}Figure 2.2 illustrates the Skeleton example in the UIQ emulator. Themouse is clicked and held on, or near, the ‘8’ digit to simulate atap and hold on the screen. The event is detected through CSkeletonUIQView::HandlePointerEventL() as shown above for digits‘1’ and ‘2.’ The iKeyState member variable is updated to reflect thescreen event, and next time the game loop runs and the screen is updated,the display for that digit highlights that the stylus is held to the screen.When the stylus (or mouse click, in the case of the emulator) is released,a pointer-up event is received and the highlight is removed.Figure 2.2Handling a pointer event received from a screen tap54SYMBIAN OS GAME BASICS2.6 System EventsAs we’ve discussed, the game loop is driven by a timer active objectand runs regularly to update the game engine internals, resulting in agiven number of frames per second.

Характеристики

Тип файла
PDF-файл
Размер
2,71 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6451
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее