Tuesday, October 28, 2014

Detecting the input device (C2/HTML5)

While getting familiar with the Construct 2, I started to wonder would it be possible somehow detect what kind of a device is used as an input device for HTML5 game. In principle, HTML5 will run on almost all platforms, so it would be very useful to see whether the player is using mouse or touch screen as a input device.

I created a simple Breakout game clone to find out how the control method could be detected easily. You can load the Construct 2 .capx file from our server, if willing to see the full example game and want to try it yourself.

Breakout clone















Game is very simple one, and it has no extra features included. I also tried to add some comments to ease up understanding what has been done and why. I am not too sure if everything is done "correct" way, but anyways this example is working somehow with my own devices (Android tablet, Lumia phone, Linux and windows computers).

Game events 2-4 are the most interesting ones from this article point of view. Please see the .capx or the picture below to see how detection was done in this case.

Detect whether mouse or touchscreen is used as input device














controlMethod variale is used to store the information about the input device.

When game is in "init" state game will wait for user input. If Touch event is triggered, game gets hint that touch screen is used as an input device and controlMethod variable value is set to "touch". Mouse detection works similar way, except it is triggered by mouse LMB release and controlMethod variable value is set to "mouse".

After mouse is clicked or touchscreen touched, the game will move to "run" state and ball starts moving. Bat object is moved horizontally towards the targetX X-coordinate on every tick. controlMethod variable is used to decide whether the bat targetX position will be based on mouse cursor position (Mouse.X), or last known touch position (Touch.X). Details can be seen from the .capx project file or the figure below.

controlMethod variable usage in "run" state

















So when the gameState is "run", loop is executed on every tick (approx. 60 times per second). When mouse cursor (of touch) is between left and right boundaries, targetX value will be set to Mouse.X or Touch.X, depending on the value of controlMethod variable. If cursor (or touch) is not between the boundaries, targetX is fixed close to left or right boundary.

Bat movement is done in events 11-14, using the "bullet" behavior. Nothing special, just defining the bat direction and then enabling/disabling the "bullet" behavior as needed.

That's it. I hope this example is useful for you.

-Jussi

No comments:

Post a Comment