Sebastian
Sebastian

Reputation: 281

Using a virtual keyboard and jQuery to trigger keypresses for a flash game

Is there a way to simulate a key press for a flash game via a virtual keyboard?

Right now I have a "virtual keyboard" which is just 1 button. When I click it, I want it to trigger the pressing of up arrow. But the event needs to be triggered in a flash game. Here's the button:

<button id="sim-up-arrow">Up</button>

Here is the flash game:

<object id="game" data="a4_truck_parking.swf"></object>

And here the jQuery/JS stuff:

$('#sim-up-arrow').on('click', function(){
    // create a new keypress event
    var e = jQuery.Event('keypress', {keyCode: 38});
    // focus the game
    $('#game').focus();
    // trigger the up arrow key press
    $('#game').trigger(e);
});

Sadly my little truck isn't accelerating.

Upvotes: 2

Views: 1382

Answers (1)

Vishkey
Vishkey

Reputation: 197

Try adding the variable "which" to your event, maybe the flash game is reading this field.

$('#sim-up-arrow').on('click', function() {
    var e = jQuery.Event('keypress', {keyCode: 38, which:38});
    // focus the game
    $('#game').focus();
    // trigger the up arrow key press
    $('#game').trigger(e);
}

Upvotes: 1

Related Questions