Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Lua Game Development Cookbook
Lua Game Development Cookbook

Lua Game Development Cookbook: Over 70 recipes that will help you master the elements and best practices required to build a modern game engine using Lua

Arrow left icon
Profile Icon Mário Kašuba
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (6 Ratings)
Paperback Jul 2015 360 pages 1st Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Mário Kašuba
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (6 Ratings)
Paperback Jul 2015 360 pages 1st Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Lua Game Development Cookbook

Chapter 2. Events

In this chapter, we will cover the following recipes:

  • Processing input events with LuaSDL
  • Using the keyboard input
  • Using the relative mouse position
  • Using the absolute mouse position
  • Using timers

Introduction

Event-driven design offers a cheap and efficient way to detect user input without the need to check for input device status in each frame. A naïve approach to this is to query all input devices for changes in their state. There are many types of input devices such as keyboard, mouse, joystick, keypad controller, tablet, touch screen, and so on. LuaSDL relies on the library libSDL 1.2, which supports only basic input devices such as keyboard, mouse, and joystick. This version doesn't support the use of multiple devices of the same kind. This limitation has been removed with libSDL 2.x, which is used in LuaSDL 2. LuaSDL 2 is the successor of a former LuaSDL library and it's in the stage of early development at the time of writing. This chapter will cover the use of an older LuaSDL library, as the LuaSDL 2 interface is not so different.

Processing input events with LuaSDL

LuaSDL offers a form of platform-independent abstraction layer to these devices with an inner event pool. You only have to query the event pool for unprocessed events and, if there are any, check for the event type.

Getting ready

Before doing any event processing, your application must initialize internal event pools. This can be achieved with the SDL.SDL_Init function, where the only parameter is a bitmask representing which parts of LuaSDL you want to initialize. You can use the bitlib library for the Lua language. Another option would be to use the bit32 internal library if you are using the newer version of the Lua interpreter. The default value here is SDL.SDL_INIT_EVERYTHING, which is fine as it starts the event pool automatically. Specifically, you can use the SDL.SDL_INIT_EVENTTHREAD or SDL.SDL_INIT_VIDEO values to initialize the event pool.

A code sample can be used to initialize the LuaSDL library. It should be used right at the start of the application...

Using the keyboard input

LuaSDL offers a simple way of determining what key was pressed or released on your keyboard. Events with event types SDL.SDL_KEYDOWN and SDL.SDL_KEYUP can react to one keystroke at the time. This is usually fine during a game play. However, if you want to use keyboard shortcuts in a text input field, the previous approach would not be very efficient.

This recipe will show you how to manage keyboard input in a robust way that can be used for both situations—to control a game or to write text into an input field.

Getting ready

Let's say you need your game character to run when a Shift key is pressed. There are three key problems. The common PC keyboard has left and right Shift keys. These are two different keys with two different key symbol codes. The next thing is that you use these keys with another keyboard key which may or may not be the modifier key. The last problem is putting key states together, so you'll know if the player has pressed the Shift...

Using the relative mouse position

The relative mouse position is often used when you need unconstrained mouse movement. A typical example of such a use is a first person shooter game in a 3D environment. The relative mouse position represents how much the mouse pointer position changed in comparison with the previous state in all the axes.

Getting ready

The biggest problem with the relative mouse position is that the mouse pointer is constrained to the application window or the screen. You can solve this by centering the mouse cursor in the center of the application window after computing the relative cursor position or by using direct values from the mouse driver.

The relative mouse position has the big advantage of versatility because you can apply the mouse cursor speed modifier simply by multiplying the relative mouse position with a number. If that number is greater than 1, the mouse cursor will move faster. Multiplying by a number lesser than 1, will slow down the mouse cursor.

How to...

Using the absolute mouse position

The absolute mouse position is used primarily in window applications, where the mouse position constraints are desirable. The mouse position (0,0) corresponds to the upper-left corner of your application window. The maximum mouse position depends always on the size of the window. Take special care when the mouse cursor is outside the application window. The behavior of LuaSDL in this situation is highly dependent on the currently used operating system! In most cases, you won't get any events related to the mouse cursor motion.

The main advantage of this is that you can use the mouse cursor position reported directly by LuaSDL to precisely manipulate GUI elements inside of the application window. This approach is used also with tablet touch input devices, where you always get absolute positions.

How to do it…

The following mouse movement handler function shows a simple way to get the absolute mouse cursor position:

[SDL.SDL_MOUSEMOTION] = function...

Using timers

LuaSDL offers support for timer objects. The problematic part is the use of timers. The LibSDL library uses callback functions to call event functions. These callbacks run in another thread and the naïve approach, where you put the Lua function in the position of callback function, would lead to Lua state corruption. There is a better way to accomplish this by using the internal LuaSDL callback function that invokes a special user event.

Timers aren't very precise and they are mostly used in GUI updates. If you need more precision, you'll need to use High Precision Event Timer (HPET), which is out of the scope of this book.

Getting ready

Each timer object uses a user-defined event that contains unique timer function identifiers represented by integer values. LuaSDL offers a slightly modified version of the SDL.SDL_AddTimer function, where it accepts two parameters instead of three. The first parameter is an interval value in milliseconds. The second is the user...

Left arrow icon Right arrow icon

Description

This book is for all programmers and game enthusiasts who want to stop dreaming about creating a game, and actually create one from scratch. The reader should know the basics of programming and using the Lua language. Knowledge of the C/C++ programming language is not necessary, but it's strongly recommended in order to write custom Lua modules extending game engine capabilities or to rewrite parts of the Lua code into a more efficient form. Algebra and matrix operations are required in order to understand advanced topics in Chapter 4, Graphics – Legacy Method with OpenGL 1.x-2.1 and Chapter 5, Graphics – Modern Method with OpenGL 3.0+. Sample demonstrations are coupled with binary libraries for Windows and Linux operating systems for convenience.

Who is this book for?

This book is for all programmers and game enthusiasts who want to stop dreaming about creating a game, and actually create one from scratch.

What you will learn

  • Set up OpenGL graphics along with GLSL shaders
  • Use lighting and graphical effects
  • Create animated game characters using Box2D library
  • Load and use textures, fonts, and 3D models
  • Design and implement a graphical user interface
  • Integrate simple Artificial Intelligence for pathfinding
  • Implement networking support
  • Use data structures in programming

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 28, 2015
Length: 360 pages
Edition : 1st
Language : English
ISBN-13 : 9781849515504
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 28, 2015
Length: 360 pages
Edition : 1st
Language : English
ISBN-13 : 9781849515504
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 136.97
L÷VE for Lua Game Programming
$32.99
Learning game AI programming with Lua
$48.99
Lua Game Development Cookbook
$54.99
Total $ 136.97 Stars icon

Table of Contents

10 Chapters
1. Basics of the Game Engine Chevron down icon Chevron up icon
2. Events Chevron down icon Chevron up icon
3. Graphics – Common Methods Chevron down icon Chevron up icon
4. Graphics – Legacy Method with OpenGL 1.x–2.1 Chevron down icon Chevron up icon
5. Graphics – Modern Method with OpenGL 3.0+ Chevron down icon Chevron up icon
6. The User Interface Chevron down icon Chevron up icon
7. Physics and Game Mechanics Chevron down icon Chevron up icon
8. Artificial Intelligence Chevron down icon Chevron up icon
9. Sounds and Networking Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(6 Ratings)
5 star 83.3%
4 star 0%
3 star 0%
2 star 0%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




CPallini Oct 01, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers a very appealing topic: game development with Lua.Leveraging on libSDL, OpenGL and several other libraries, illustrates, in the formof recipes, many techniques required to build yourself a game, game engine orprototype.Since the topic is wide and deep, it is a condensed book, rich of content inrelatively few pages: from directory organization, module and error handling, Luainteraction with C++, to game UI, physics, AI, sound and network communication,passing for the event driven SDL game loop, OpenGL (both the older immediate mode and the moremodern shading language).I found most of the content interesting, some recipes a bit difficult tounderstand at first (in my opinion delaying the explanation in 'how it works'section is a bit confusing), neverhtless worthy to be studied.A relatively good knowledge of Lua is required to fully understand the recipes(while proficience with modern C++ would help for actual game development).The approach is pragmatic and you have to use the companion code in order toappreciate the book and start experimenting (I should say compiling myself therequired libraries was not exactly 'a breeze' like the author claims in the book).All in all it is a solid, pragmatic, fairly advanced book: enough to make youappreciate the efforts required in game development and possibly desire to deepenyour knowledge about the related problems and techniques.
Amazon Verified review Amazon
Julie Blanchard Feb 07, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Bought for my sons Christmas presentHe loves it
Amazon Verified review Amazon
Dan Kosko Nov 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
quick delivery. just as described. good job
Amazon Verified review Amazon
Kiffin Gish Oct 27, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you've ever fantasized about creating your own fancy game but never was able to get beyond the basics, then this is the right place to begin. Starting with the first chapters, you become more familiar with the Lua programming language and what goes into a powerful gaming engine. Slowly but surely, your learn how Lua provides the ideal playground to build up a solid platform of modules and components that can be combined nicely. It's not just about the complex concepts that go into designing games but also the choice of the right programming language and how to use it effectively. By the end of the book you start mastering the more difficult concepts and can deal with all the fancy algorithms that go into good game making.
Amazon Verified review Amazon
Joel A. Sundquist Apr 19, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great lua book. Even if you are not developing games it has some helpful performance tips
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.